chore(history): squash 59 commit(s) from 2026-09-23
- refactor(hud/weather/render): Scoreboard 931→240 + Rain 903→159 + UiMeshGeometry 956→99 (8.5.2) - refactor(chams): Chams 985 → 129 + 4×≤195 (8.5.2) - refactor(module): Module 1031 → 139 + 4×≤134 (8.5.2) - refactor(tooltips): BetterTooltips 960 → 181 + 4×≤199 (8.5.2) - refactor(clickgui): ClickGuiPickerState 970→166 + ModulesMenuScreen 966→145 (8.5.2) - refactor(clickgui): CombatProtocolHeuristicsEditorState 932→79 + 4×≤192 (8.5.2) - refactor(hud): CompactHudStatModel 894 → 125 + 4×≤175 (8.5.2) - refactor(iris): ShaderPatchCompiler 843→66 + 4×≤174 (8.5.2) - refactor(tab): CustomTabList 834→136 + 4×≤166 (8.5.2) - refactor(relations): OnlineRelationPlayerPickerComponent 837→74 + 4×≤192 (8.5.2) - refactor(hits): HitEffect 770→120 + 4×≤176 (8.5.2) - refactor(predict): Predictions 815→150 + 4×≤195 (8.5.2) - refactor(config): ConfigProfilesComponent 799→125 + 4×≤195 (8.5.2) - refactor(sim): PlayerMovementSimulation 757→157 + 4×≤194 (8.5.2) - refactor(predict): ProjectilePuncher 747→104 + 3×≤134 (8.5.2) - refactor(crosshair): Crosshair 743→143 + 4×≤167 (8.5.2) - refactor(mediaplayer): MediaPlayer 743→174 + 4×≤196 (8.5.2) - refactor(hud): Itemizer 699→193 + Cooldowns 707→151 (8.5.2) - refactor(hud): Potions 617→176 + 4×≤166 (8.5.2) - refactor(hud): Admins 702→118 + 4×≤138 (8.5.2) - refactor(hud): Keybinds 611→157 + 4×≤160 (8.5.2) - refactor(hud): ModuleList 499→181 + 3×≤150 (8.5.2) - refactor(hud): Radar 392→161 + 2×≤124 (8.5.2) - refactor(hud): Fps 309→168 + 3×≤107 (8.5.2) - refactor(hud): Memory 304→151 + 3×≤144 (8.5.2) - refactor(hud): Tps 339→154 + 3×≤143 (8.5.2) - refactor(hud): Ping 309→145 + 3×≤125 (8.5.2) - refactor(hud): SpeedBps 334→156 + 3×≤142 (8.5.2) - refactor(hud): GameTime 314→150 + 3×≤127 (8.5.2) - refactor(hud): SystemTime 300→136 + 3×≤130 (8.5.2) - refactor(hud): Coordinates 337→174 + 2×≤172 (8.5.2) - refactor(hud): Armor 324→162 + 2×≤148 (8.5.2) - refactor(hud): Inventory 476→153 + 3×≤181 (8.5.2) - docs(todo): обновлён 8.5.2 — отмечены готовые гиганты (BetterButtons/InventorySwap/Svg/Темы/WorldParticles/Module/Chams и хвост) - docs(api): папка combatant-client-26.2/docs + addons.md (API можно ломать при рефакторе) - refactor(visuals): BlockHighlight 692→271 + 4×≤200 (8.5.2) - refactor(mixins): GameRendererMixin 830→344 (хуки) + 4 хелпера (8.5.2) - refactor(visuals): WorldParticles 821→260 + 6×≤200, режимы добиты (8.5.2) - docs(todo): 8.5.2 — WorldParticles/GameRendererMixin/BlockHighlight отмечены ГОТОВО - refactor(render): MeshBuilder 738→447 (фасад write-API) + 3 хелпера, FrameStats снесён (8.5.2) - docs(todo): Фаза 10 — дизайн платформы (аккаунты/конфиги/аватарки), backlog RPC-чата - docs(todo): Подсистема 3 — Аддоны 2.0 (скрипты/версии) + витрина аддонов + админка - docs(todo): Подсистема 2 — RPC-чат/друзья/виджеты-телеметрия + рейт-лимиты, доп. правки Подсистемы 3 - chore: переименование combatant-client-26.2 -> mod, добавлены backend/ и frontend/ - docs(backend): implementation plan for accounts-service (Подсистема 1, часть 1) - chore: пересоздать backend/frontend через cargo new и bun create vite + tailwind; убрать таблицу компонентов из TODO.md - docs(backend): edition 2024 в плане вместо 2021 - chore: обновить версии до реально актуальных (проверено компиляцией) - docs: правила платформы (лимит 250 строк, антипаттерны backend/frontend по итогам ресёрча) + frontend/ARCHITECTURE.md - docs: добавить правило ≤4 файла на папку в правила платформы (backend/frontend) - docs: commit messages in English from now on - chore: gitignore .superpowers/ scratch directory - docs: commit messages in English from now on (mod) - feat(backend): scaffold accounts-service with health check - chore(backend): remove target/ build artifacts from git, add gitignore - chore: track docs/ in git (was accidentally gitignored, never committed) - chore(backend): convert to Cargo workspace, plan full microservice layout - feat(backend): accounts/avatars/device_links schema + migration - feat(backend): argon2id password hashing
This commit is contained in:
parent
ec10395511
commit
9d08fa910a
2239 changed files with 35265 additions and 28110 deletions
45
mod/.gitignore
vendored
Normal file
45
mod/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
# === Gradle ===
|
||||
.gradle/
|
||||
build/
|
||||
out/
|
||||
|
||||
# === IntelliJ IDEA / Eclipse / VSCode ===
|
||||
.idea/*
|
||||
!.idea/misc.xml
|
||||
*.iml
|
||||
.classpath
|
||||
.project
|
||||
.settings/
|
||||
.vscode/
|
||||
|
||||
# === Logs / Cache ===
|
||||
logs/
|
||||
run/
|
||||
cache/
|
||||
*.log
|
||||
|
||||
# === OS-specific ===
|
||||
Thumbs.db
|
||||
.DS_Store
|
||||
|
||||
# === Exported / Generated files ===
|
||||
exports/
|
||||
export/
|
||||
export_cache/
|
||||
*.jar
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
*.zip
|
||||
/local-maven/
|
||||
/to-do-list
|
||||
/.tmp/
|
||||
/.tmp_mc/
|
||||
/.tmp_sodium/
|
||||
/.tmp_iris/
|
||||
/.tmp_photon/
|
||||
/.tmp_complementary/
|
||||
/!new_temp_assets/
|
||||
/src/main/resources/javet/natives/libjavet-v8-linux-x86_64.v.5.0.9.so
|
||||
/src/main/resources/javet/natives/libjavet-v8-macos-x86_64.v.5.0.9.dylib
|
||||
/src/main/resources/javet/natives/libjavet-v8-windows-x86_64.v.5.0.9.dll
|
||||
/RELEASE_CHECKLIST.md
|
||||
/.claude/
|
||||
297
mod/DEV_GUIDE.md
Normal file
297
mod/DEV_GUIDE.md
Normal file
|
|
@ -0,0 +1,297 @@
|
|||
# LoVisual Mod — Dev Guide (Единый справочник)
|
||||
|
||||
Цель: быстро добавить модуль / HUD-элемент / команду / миксин, не перекапывая весь код. Сводка по реальному коду, объединено из `DEV_GUIDE.md` + `DEVELOPMENT.md`.
|
||||
|
||||
- Пакеты: `dev.loki.lovisual.*`
|
||||
- Стек: **Java 25 · Fabric Loader 0.19.3 · Minecraft 26.2** (Fabric Loom), Lombok
|
||||
- Правила — нарушение = откат (см. §2)
|
||||
|
||||
---
|
||||
|
||||
## 1. Сборка и запуск
|
||||
|
||||
```bash
|
||||
cd combatant-client-26.2
|
||||
./gradlew build # jar: build/libs/lovisual-<ver>.jar
|
||||
./gradlew test # юнит-тесты (~320)
|
||||
./gradlew runClient # dev-запуск Minecraft с модом
|
||||
./gradlew runClient --rerun-tasks # если кэш врёт
|
||||
```
|
||||
|
||||
Готовый jar для теста в реальном инстансе:
|
||||
|
||||
```bash
|
||||
cp build/libs/lovisual-*.jar /storage/prismlauncher/instances/26.2/minecraft/mods/
|
||||
```
|
||||
|
||||
Ресурсы: **только настоящие PNG** (сигнатура `89 50 4E 47`). JPEG, переименованный в `.png`, уронит `Bad PNG Signature` при загрузке.
|
||||
|
||||
---
|
||||
|
||||
## 2. Правила проекта (ОБЯЗАТЕЛЬНЫЕ)
|
||||
|
||||
- **KISS / DRY / SOLID** — просто, без оверинжиниринга.
|
||||
- **≤200 строк на файл.** Фасад-делегат (`Renderer2D`, `Module` ≈1181) — исключение; больше логики → выноси `package-private` хелперы в тот же пакет.
|
||||
- **≤4 файла на папку** — больше → новая подпапка по смыслу.
|
||||
- **Никакого статика от Minecraft**: `Minecraft.getInstance()` только локальной переменной в месте использования, никогда в поле. `INSTANCE` — только для сервисов без lifecycle.
|
||||
- **Lifecycle гейты**: `Lifecycle.isActive()/canRunRender()/canRunHud()` — до `activate()` события/тики не работают; `EventBus.post()` сам гейтит.
|
||||
- **Никаких this-escape** — конструктор не публикует `this`.
|
||||
- **Никаких мёртвых миксинов** — миксин только если реально нужен; `cancellable=true` только при реальном `cancel`.
|
||||
- **`dev.loki.lovisual.mixins.*` — ТОЛЬКО классы с `@Mixin`.** Обычный хелпер там крашит `IllegalClassLoadError` (Knot). Хелперы — в `util/` или пакет фичи (см. `HandDynamics`).
|
||||
- **Без пустышек** — файл без реализации не создаётся.
|
||||
- **Каждый этап компилируется**: `./gradlew build` перед коммитом.
|
||||
- **Тесты обязательны** для новой чистой логики (JUnit 5, без моков Minecraft — выноси математику в `static` и тесть).
|
||||
- **Референсы (`ref/`)** — чужой код (SoupVisuals SOUP-1.0, Delta и др.): **только идеи**, пере-реализация под наши правила, никакого копирования.
|
||||
- **`System.currentTimeMillis()` в модулях → `GameClock.millis()`**, `static final Minecraft` в полях — баг.
|
||||
|
||||
---
|
||||
|
||||
## 3. Карта пакетов
|
||||
|
||||
```
|
||||
dev.loki.lovisual
|
||||
├── LoVisual.java — ClientModInitializer: старт (тики, рендер-фазы)
|
||||
├── Lifecycle.java — INIT → ACTIVE → SHUTDOWN; гейты
|
||||
├── events/ — EventBus (@EventHandler, приоритеты, гейт по Module)
|
||||
│ └── impl/ — GameTickEvent, PacketEvent, AttackEntityEvent, LightmapModifyEvent...
|
||||
├── config/ — MainConfig, SettingDef, .lvcfg (legacy .cbcfg читается)
|
||||
│ ├── values/ — ConfigValue: bool/num/mode/color/set/... (есть тесты)
|
||||
│ └── profile/ — профили (collect/apply/diff/binary codec)
|
||||
├── features/
|
||||
│ ├── module/ — СИСТЕМА МОДУЛЕЙ (главное)
|
||||
│ │ ├── Module.java — базовый класс
|
||||
│ │ ├── ModuleInfo — @annotation
|
||||
│ │ ├── ModuleManager — реестр + диспетчер фаз
|
||||
│ │ ├── ModuleAutoLoader — ClassGraph по @ModuleInfo (no-args ctor → postInit)
|
||||
│ │ ├── Modules — Modules.get(Класс.class) / enabled(id)
|
||||
│ │ ├── ModuleCategory — COMBAT/MOVEMENT/PLAYER/VISUALS/MISC (легит-направление: читы удаляем)
|
||||
│ │ ├── HudPhase / WorldPhase — фазы рендера
|
||||
│ │ └── modules/{combat,player,visuals,misc}/
|
||||
│ ├── command/ — @CommandInfo + ClientCommand (ClassGraph, префикс %)
|
||||
│ ├── gui/
|
||||
│ │ ├── clickgui/ — экран настроек (Setting → виджет)
|
||||
│ │ └── hud/ — HUD-элементы
|
||||
│ │ ├── draggable/ — перетаскиваемые (Fps, Coords, ModuleList, TargetHud…)
|
||||
│ │ └── nondraggable/ — статичные (CustomBar, BetterChat, BetterButtons, DynamicIsland…)
|
||||
│ ├── relations/ — друзья/враги (PlayerRelations, CategoryService)
|
||||
│ ├── security/ — BackdoorProtection (SSRF/translate)
|
||||
│ └── theme/ — Themes.Theme (windowBg/header/surface/accent...), Theme.theme()
|
||||
├── render/engine/ — Renderer2D/3D, пайплайны, шрифты, MeshBuilder
|
||||
│ ├── renderer/Renderer2D — 2D (quad/roundedRect/circle/line/item/svg/effect)
|
||||
│ ├── renderer/Renderer3D — 3D (line/quad/triangle)
|
||||
│ ├── text/ — Fonts.renderer("Onest", Regular), TextRenderer
|
||||
│ ├── animation/AnimationUtility
|
||||
│ ├── pipeline/LoVisualRenderPipelines — UI_COLORED, WORLD_COLORED, HAND_*, SHADER_ESP_*, POST_FX...
|
||||
│ └── uniform/MeshBuilder
|
||||
├── mixins/ — @Mixin-классы (mixins.json, LoVisualMixinPlugin)
|
||||
│ └── mixins/accessors/ — MinecraftAccessor, PlayerInventoryAccessor...
|
||||
│ └── mixininterface/ — IGuiGraphics, IEntity...
|
||||
├── addon/ + api/v0/ — система аддонов (LoVisualAddon, LoVisualModuleExtension, RenderCallback)
|
||||
└── util/ — хелперы: target, pvp, aiming, time/GameClock, input/KeyManager, screen, text, raycast...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Жизненный цикл и старт
|
||||
|
||||
В `LoVisual.onInitializeClient()` по порядку:
|
||||
1. `LoVisualRenderEngineBootstrap.init()`, `PostProcessManager.register(...)`
|
||||
2. `MainConfig.get()`, `AccountConfig.get()`, `CommandManager.init()`, `MediaSessionService`
|
||||
3. `ModuleAutoLoader.load("dev.loki.lovisual.features.module.modules")` — ищет `@ModuleInfo`, `new` + `postInit()`
|
||||
4. `ModuleManager.loadAllModuleConfigs()` — применяет `.lvcfg`, включает `enabled`
|
||||
5. `HudElements.init()`, `StaticHudElementBootstrap.init()`
|
||||
6. `Events.BUS.register(...)` — глобальные сервисы (`RotationManager`, `PvpTracker`...)
|
||||
7. `Lifecycle.activate()` — после этого тики/события/рендер работают
|
||||
|
||||
**Вывод:** новый модуль — просто класс с `@ModuleInfo` в `...modules.<категория>`; регистрировать руками не нужно.
|
||||
|
||||
---
|
||||
|
||||
## 5. Модуль — быстрый старт
|
||||
|
||||
```java
|
||||
package dev.loki.lovisual.features.module.modules.misc;
|
||||
|
||||
import dev.loki.lovisual.config.values.primitive.NumberValue;
|
||||
import dev.loki.lovisual.events.meta.EventHandler;
|
||||
import dev.loki.lovisual.events.impl.render.GameTickEvent;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.core.ModuleCategory;
|
||||
import dev.loki.lovisual.features.module.core.ModuleInfo;
|
||||
|
||||
@ModuleInfo(id = "my_feature", displayName = "My Feature", category = ModuleCategory.MISC)
|
||||
public class MyFeature extends Module {
|
||||
private final NumberValue<Integer> amount = num("myFeatureAmount", 3, 0, 20);
|
||||
|
||||
@Override public void onEnable() {}
|
||||
@Override public void onDisable() {}
|
||||
@Override public void onTick() {
|
||||
if (!isEnabled()) return;
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc.level == null) return;
|
||||
}
|
||||
@EventHandler private void onTick(GameTickEvent e) {}
|
||||
}
|
||||
```
|
||||
|
||||
`@ModuleInfo`: `id` (snake, уникальный, ключ конфига/команды), `displayName`, `aliases`, `category`, `enabledByDefault`, `description` (i18n).
|
||||
|
||||
Автогенерируемые поля `Module`: `enabled`/`bind`/`activation_source`/`show_in_module_list` (`postInit` → `SettingFactory.fromDefs` → `ModuleManager`).
|
||||
|
||||
Хуки: `onEnable/onDisable/onTick/onFrame/onKey/onRender2D/onRenderHudEngine/onRenderWorldEngine`, `getHudPhase()/getWorldPhase()` (по умолч. `NONE` — не рендерится). Управление: `isEnabled()/toggle()/setEnabled()`, `isAvailable()`, `Modules.get(Freecam.class)`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Настройки (ConfigValue → SettingDef)
|
||||
|
||||
База `ConfigValue<T>`: `get()/set()/getName()/toJson()/fromJson()`.
|
||||
|
||||
Хелперы в `Module`/`BaseHudElement` (`protected final`):
|
||||
|
||||
| Хелпер | Тип | Пример |
|
||||
|--------|-----|--------|
|
||||
| `bool(name, def)` | `BooleanValue` | `bool("my_on", true)` |
|
||||
| `num(name, def, min, max)` | `NumberValue` | `num("my_num", 3, 0, 20)` |
|
||||
| `mode(name, def, opts...)` | `ModeValue` | `mode("my_mode", "A", "A","B")` |
|
||||
| `enumMode(name, defEnum)` | `EnumValue` | см. `Reach` |
|
||||
| `color(name, "#AARRGGBB")` | `RGBAColorValue` | `color("my_bg", "#F7343434")` |
|
||||
| `text/textList/itemList/group/bind/action` | `StringValue/SetValue/ItemIdSetValue/...` | `itemList("my_items")` |
|
||||
|
||||
`*Common` варианты (`boolCommon/numCommon/enumCommon`) берут схему из `CommonSettingSchemas`.
|
||||
|
||||
Условность: `visibleWhen(numCommon(...), () -> cond)`, `appliesWhen(setting, () -> mc.player!=null, "Только в мире")`. Экшены: `action("climb","G", PRESS)` → `isActionPressedOnce("climb")`.
|
||||
|
||||
HUD-элементы объявляют настройки в `defineSettings(List<SettingDef>)`; модули — полями (автоматом). Виджеты `SettingDef.Kind`: `BOOLEAN, NUMBER, MODE, COLOR, TEXT, TEXT_LIST, GROUP, BIND...` (`@DisableSettingI18n`).
|
||||
|
||||
---
|
||||
|
||||
## 7. HUD-элементы
|
||||
|
||||
**Draggable** (`hud/draggable/impl/`, `@HudElementInfo(id, displayName, enabledByDefault, order)`, `DraggableHudElement`): `applyDefaultPosition(w,h)`, `renderEngine(Renderer2D, TextRenderer, GuiGraphicsExtractor, tickDelta, w,h)`, `usesEngineRenderer()=true`, `x/y/width/height`.
|
||||
|
||||
**Static** (`hud/nondraggable/impl/`, `@HudElementRegister(order)`, `AbstractHudElement` `super(id,"Title",defaultEnabled)` + `INSTANCE`): для вкладки UI добавить `new StaticHudCard(...)` в `MenuSettingsResolver.STATIC_UI_CARDS`. Тема: `Theme.theme().accent()/windowBg()`, `HudRenderUtil.setAlpha/mixColor`, текст `Fonts.renderer(...)`.
|
||||
|
||||
---
|
||||
|
||||
## 8. Команды
|
||||
|
||||
`ClientCommand` + `@CommandInfo(id, aliases, usage, descriptionKey)`, регистрация в `CommandManager` (ClassGraph). Префикс **`%`** (legacy `@`). `CommandPrefix` — источник истины; автокомплит `suggest()` + `UsageHints`.
|
||||
|
||||
```java
|
||||
@CommandInfo(id="toggle", aliases="t", usage="%toggle <module> [on|off]", descriptionKey="command.toggle.description")
|
||||
public final class ToggleCommand implements ClientCommand {
|
||||
public boolean execute(CommandContext ctx){ CommandOutput.success("Done"); return true; }
|
||||
public List<String> suggest(CommandContext ctx,int i,String token){ return List.of(); }
|
||||
}
|
||||
```
|
||||
|
||||
`CommandContext.arg(i)`, `CommandOutput.success/warning/error`.
|
||||
|
||||
---
|
||||
|
||||
## 9. События (EventBus)
|
||||
|
||||
`Events.BUS.post(event)` → `@EventHandler(priority=N)` (один аргумент-`Event`). Модули гейтятся `isEnabled()`. `Event` имеет `cancel()`.
|
||||
|
||||
`events/impl/` : `GameTickEvent`, `PacketEvent`, `AttackEntityEvent`, `EventBreakBlock`, `LightmapModifyEvent`, `PlayerMoveEvent`, `RenderPrewarmCollectEvent`...
|
||||
|
||||
```java
|
||||
@EventHandler private void onTick(GameTickEvent e){ }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 2D-рендер (HUD)
|
||||
|
||||
Фазы `getHudPhase()`: `FIRST, BEFORE_MISC_OVERLAYS, AFTER_MISC_OVERLAYS, AFTER_BOSS_BAR, BEFORE_DEMO_TIMER, BEFORE_CHAT, AFTER_SUBTITLES, LAST` → `onRenderHudEngine`.
|
||||
|
||||
`Renderer2D` (фасад, `begin()/render()` делает диспетчер): `quad/roundedRect/roundedRectGradient/circle/line/item/svg/effect`. Текст: `Fonts.renderer("Onest", Regular, textRenderer).begin(scale,true,false) → getWidth/render → end()` или `textRenderer.begin...`. Анимации `AnimationUtility`, хелперы `HudRenderUtil`/`HudGlobalConfig`/`Theme.theme()`.
|
||||
|
||||
---
|
||||
|
||||
## 11. 3D-рендер (мир)
|
||||
|
||||
Фазы `getWorldPhase()`: `BEFORE_ENTITIES, AFTER_ENTITIES, BEFORE_TRANSLUCENT, END_MAIN, AFTER_POST_PROCESS` → `onRenderWorldEngine(Renderer3D, Renderer3D, tickDelta)`.
|
||||
|
||||
Простой путь: `renderer.begin(); renderer.line(...); renderer.quad(...); renderer.render(new PoseStack());` (см. `Tracers`). Продвинутый: `MeshBuilder` + `LoVisualRenderPipelines` (`UI_COLORED, WORLD_COLORED...`). `Renderer3D.Cull.isInFrustum`.
|
||||
|
||||
---
|
||||
|
||||
## 12. Миксины и accessors
|
||||
|
||||
Все в `mixins/` (`@Mixin`), реестр `lovisual.mixins.json` (`LoVisualMixinPlugin`). Accessors в `mixins/accessors/` (`PlayerInventoryAccessor`...), `mixininterface/` (`IGuiGraphics`). Правило: только `@Mixin` в `mixins.*`.
|
||||
|
||||
---
|
||||
|
||||
## 13. Конфиг, профили и i18n
|
||||
|
||||
Модули/HUD → `<game>/lovisual/*.lvcfg` (legacy `.cbcfg` читается). Профили `config/profile/` (ClickGUI → Configs).
|
||||
|
||||
i18n `assets/lovisual/lang/{en_us,ru_ru}.json`:
|
||||
- модуль `module.<id>.description`, `setting.<id>.<setting_id>`, `option.<Option>`
|
||||
- draggable `hud.draggable.<id>`, static `setting.hud_element.<id>.<key>`, команды `command.<id>.description`, общие `setting.common.<key>`
|
||||
|
||||
Пропущенный ключ ловит `MissingI18nReporter` в dev.
|
||||
|
||||
---
|
||||
|
||||
## 14. Полезные утилиты (`util/`)
|
||||
|
||||
`TargetManager`, `PvpTracker`, `RotationManager`, `GameClock.millis()`, `TimerController`, `KeyManager`, `ClientScreen`, `PlayerSimulationCache`, `OmniItemUtils`, `DebugLog`, `RenderResourceReadiness`, `CategoryService`, `FastFps`...
|
||||
|
||||
Ленивый `Minecraft.getInstance()` — только локально.
|
||||
|
||||
---
|
||||
|
||||
## 15. API для аддонов (`api/v0/`)
|
||||
|
||||
`LoVisualAddon` (`onConfigureModules/onInitialize/onClientReady/onShutdown`), `LoVisualModuleExtension` (`beforeEnable/afterEnable/beforeTick...`), `LoVisualClientApi.get().modules()/isModuleEnabled()`, `LoVisualRenderCallback` (`HUD_RAW, WORLD_...`), `LoVisualClickGuiSection`.
|
||||
|
||||
---
|
||||
|
||||
## 16. Тесты
|
||||
|
||||
`src/test/java/` зеркалит `main`, **только чистая логика** (без MC рантайма): `util/text/NameProtectorTest`, `config/values/*Test`, `config/profile/ConfigProfileValueCodecTest`, `events/EventBusTest` (нужен `Lifecycle.activate()`).
|
||||
|
||||
Выноси `static int tint(...)` / `record Layout(...)` и тесть.
|
||||
|
||||
---
|
||||
|
||||
## 17. Чек-лист нового модуля / перед коммитом
|
||||
|
||||
1. `@ModuleInfo` в `modules/<категория>/`, `extends Module`, `onEnable/onTick` + `@EventHandler` если нужно
|
||||
2. Настройки хелперами (`num/bool/color/visibleWhen`), `i18n` в оба `lang` файла
|
||||
3. Рендер: верни `getHudPhase()/getWorldPhase()` + `onRenderHudEngine/onRenderWorldEngine`
|
||||
4. `./gradlew build` зелёный, `./gradlew test` зелёный, файл ≤200, папка ≤4, нет `static Minecraft` в полях, нет `System.currentTimeMillis()` → `GameClock`, нет пустышек/мёртвых миксинов, `mixin` только `@Mixin`
|
||||
5. `TODO.md` отмечен, `ref/` не копировался
|
||||
|
||||
**Не делай:** `static final Minecraft` в полях, `this`-escape, мёртвый код, копипаст чужого `ref/`.
|
||||
|
||||
---
|
||||
|
||||
## 18. Современные рекомендации (2025-2026, web-поиск)
|
||||
|
||||
### Clean Code — без догматизма
|
||||
- **YAGNI** «You Aren't Gonna Need It» — не пиши на будущее; **KISS** > OCP в быстро меняющемся коде. Принцип — эвристика, не закон.
|
||||
- **DRY ловушка**: дублирование дешевле неверной абстракции (Sandi Metz). Выноси только *семантически* одинаковое, синтаксически похожее `for`-циклы — не повод для хелпера → лишняя связность.
|
||||
- **SOLID критика**: ортодоксальный SOLID плодит `Service → RepoInterface → RepoImpl → QueryBuilder`, низкая связность, но нечитаемо и 15× медленнее (Casey Muratori «Clean Code, Horrible Performance» 2023: замена полиморфного OCP на `switch` дала 15×). Применяй умеренно, только где абстракция реально нужна.
|
||||
- **Читаемость**: без глубокой вложенности — guard-clauses `if (user==null) return;`, без магических чисел → `static final MIN_DRINKING_AGE=21`, говорящие имена `customerOrderHistoryList` > `list`, комментарии *почему*, а не *что*, консистентное форматирование, DI вместо `new`.
|
||||
|
||||
### Java 21/25 (LTS)
|
||||
- `if (obj instanceof String s)` / `record Point(int x,int y)` + `if (o instanceof Point(int x,int y))` / `switch` с pattern-matching и `case null`, `sealed interface Command permits Get,Put,Delete` — меньше кастов, безопаснее API.
|
||||
- **Virtual threads** — не «pixie dust»; дают выигрыш на I/O-bound, но не на CPU-bound. **ScopedValue** (финал JDK25) + **Structured Concurrency** (preview JDK25) лучше `ThreadLocal` по памяти/синхронизации, особенно с виртуальными потоками.
|
||||
- **JDK25 perf**: `String.hash` `@Stable` → константная свёртка `Map.of("constant",...)`, `Stable Value` preview, `ForkJoinPool` теперь `ScheduledExecutorService` (быстрее отмена timeout), ML-KEM/ML-DSA квантостойкая криптография ×2 на AVX-512/ARM, `HKDF` и др. — просто обнови JDK, код ускорится без изменений.
|
||||
|
||||
### Secure Coding (OWASP Java Cheat Sheet)
|
||||
- **Injection**: только параметризация (`PreparedStatement`, JPQL `setParameter`), не конкатенация строк; для `isReachable` вместо `Runtime.exec("ping "+host)`.
|
||||
- **XSS**: `OWASP Java HTML Sanitizer` + `OWASP Java Encoder` (`Encode.forHtml`) при выводе к пользователю.
|
||||
- **Крипто**: никогда не пиши своё — используй JCA/JCE, `AES-GCM` + `ECDH`, каждый раз новый `nonce`, секреты — через cloud secret manager, ключи ротируй. Слабые `MD5/DES` запрещены `JEP 565` в Java 21.
|
||||
|
||||
### Fabric / Mixin (2025-2026)
|
||||
- Порядок предпочтения: `@Inject` (callback, стекается) > `MixinExtras @WrapOperation/@ModifyExpressionValue` > `@Redirect/@ModifyConstant` (только один на таргет → конфликт) > `@Overwrite` (почти никогда).
|
||||
- `@Unique modid$field`, абстрактный mixin-класс (не надо имплементить интерфейсы родителя), `@Shadow` для доступа, `(Target)(Object)this` для `this`, внутренние классы `Outer$Inner`.
|
||||
- Сеть: пакеты приходят на net-thread — парсь там, а доступ к `Minecraft`/`Level` только через `client.execute` / task-queue на main thread.
|
||||
- Избегай `java.awt/javax.swing` — вешает игру; не патчи Fabric API напрямую, ищи `FabricBlockSettings` и т.п.
|
||||
|
||||
*Источники: Medium 2025 DRY/KISS/YAGNI, Baeldung Clean Code, JavaCodeGeeks Dark Side SOLID, Oracle Inside Java 2025-2026, Fabric Wiki mixin_tips, OWASP Java Security Cheat Sheet.*
|
||||
|
||||
674
mod/LICENSE
Normal file
674
mod/LICENSE
Normal file
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
150
mod/README.md
Normal file
150
mod/README.md
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
<div align="center">
|
||||
|
||||
# LoVisual
|
||||
|
||||
Minecraft utility client for PvP and automation.
|
||||
Developed and maintained by loki5512344.
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
[English](#english) | [Русский](#русский)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## English
|
||||
|
||||
### Overview
|
||||
|
||||
LoVisual is an open-source legit utility client for Minecraft. It provides configurable visual, HUD, and UI features with a custom ClickGUI, theme system, and addon API.
|
||||
|
||||
LoVisual is developed and maintained by [loki5512344](https://github.com/loki5512344). The goal is to keep adding new features and maintain compatibility with the latest Minecraft versions.
|
||||
|
||||
### Quick Start
|
||||
|
||||
1. Install Fabric Loader 0.19.3+ for MC 26.2+
|
||||
2. Download the LoVisual jar
|
||||
3. Place it in your `mods/` folder along with Fabric API and Sodium
|
||||
4. Open the ClickGUI with **`RShift`** (configurable)
|
||||
|
||||
### Features
|
||||
|
||||
| Feature | Description |
|
||||
|---------|-------------|
|
||||
| Combat | ProjectilePuncher, Reach, RubberHand, SpearAssist, TPSSync, PvpCooldowns, NoFriendDamage, TargetESP, Predictions, DamageTint |
|
||||
| Visuals | ESP, NameTags, Chams, Crosshair, FullBright, MotionBlur, NoRender, Freecam, Hitboxes, Light, ChinaHat, Trinkets, and more |
|
||||
| Player | AutoTool, ClickPearl, FakeLag, NoDelay, LockSlot, AutoRespawn, DeathCoords, NoInteract |
|
||||
| Misc | BetterMinecraft, FakePlayer, HitSounds, NameProtect, MessageFilter, NoSound, DefineTarget |
|
||||
| HUD | Draggable & static elements: TargetHUD, ModuleList, Watermark, Reach, Armor, Potions, Keystrokes, Coords, Notifications, Scoreboard |
|
||||
| ClickGUI | Full-featured GUI with module browser, settings editor, theme editor, config profiles |
|
||||
| Config profiles | `.lvcfg` profiles for modules, HUD, and themes — shareable between users |
|
||||
| Addon API | Versioned addon API for extending the client |
|
||||
| Custom renderer | Custom UI rendering with MSDF fonts, SVG icons, and shader support |
|
||||
| Iris/Sodium/Xaero | Optional compatibility with popular mods |
|
||||
|
||||
### Compatibility
|
||||
|
||||
| Mod | Status |
|
||||
|-----|--------|
|
||||
| Sodium | ✅ Required |
|
||||
| Iris | ✅ Optional — shaderpack support |
|
||||
| ImmediatelyFast | ✅ Optional — performance |
|
||||
| Entity Culling | ✅ Optional — performance |
|
||||
| Xaero's Minimap | ✅ Optional — waypoint integration |
|
||||
| Xaero's World Map | ✅ Optional — waypoint integration |
|
||||
| ViaFabricPlus | ✅ Optional — protocol translation |
|
||||
|
||||
### Dependencies
|
||||
|
||||
- **Required:** Fabric Loader 0.19.3+, Fabric API, Sodium, Java 25+
|
||||
- **Optional:** Iris, ImmediatelyFast, ViaFabricPlus, Entity Culling, Xaero's Minimap, Xaero's World Map
|
||||
|
||||
### Installation
|
||||
|
||||
1. Download the jar from [Releases](../../releases)
|
||||
2. Place it in your `mods/` folder
|
||||
3. Restart the game
|
||||
|
||||
---
|
||||
|
||||
## Русский
|
||||
|
||||
### Обзор
|
||||
|
||||
LoVisual — открытый легитный утилитарный клиент для Minecraft. Включает настраиваемые визуальные, HUD и UI-модули, кастомный ClickGUI, систему тем и API для аддонов.
|
||||
|
||||
LoVisual разрабатывается и поддерживается [loki5512344](https://github.com/loki5512344). Цель — добавлять новые возможности и поддерживать актуальные версии Minecraft.
|
||||
|
||||
### Быстрый старт
|
||||
|
||||
1. Установите Fabric Loader 0.19.3+ для MC 26.2+
|
||||
2. Скачайте LoVisual jar
|
||||
3. Положите в папку `mods/` вместе с Fabric API и Sodium
|
||||
4. Откройте ClickGUI через **`RShift`** (настраивается)
|
||||
|
||||
### Возможности
|
||||
|
||||
| Возможность | Описание |
|
||||
|-------------|----------|
|
||||
| Combat | ProjectilePuncher, Reach, RubberHand, SpearAssist, TPSSync, PvpCooldowns, NoFriendDamage, TargetESP, Predictions, DamageTint |
|
||||
| Visuals | ESP, NameTags, Chams, Crosshair, FullBright, MotionBlur, NoRender, Freecam, Hitboxes, Light, ChinaHat, Trinkets и другие |
|
||||
| Player | AutoTool, ClickPearl, FakeLag, NoDelay, LockSlot, AutoRespawn, DeathCoords, NoInteract |
|
||||
| Misc | BetterMinecraft, FakePlayer, HitSounds, NameProtect, MessageFilter, NoSound, DefineTarget |
|
||||
| HUD | Перетаскиваемые и статические элементы: TargetHUD, ModuleList, Watermark, Reach, Armor, Potions, Keystrokes, Coords, Notifications, Scoreboard |
|
||||
| ClickGUI | Полноценный GUI с браузером модулей, редактором настроек, тем и профилей конфигов |
|
||||
| Профили `.lvcfg` | Профили для модулей, HUD и тем — можно шарить между пользователями |
|
||||
| Addon API | Версионированное API для аддонов |
|
||||
| Кастомный рендер | UI-рендеринг с MSDF-шрифтами, SVG-иконками и шейдерами |
|
||||
| Iris/Sodium/Xaero | Опциональная совместимость с популярными модами |
|
||||
|
||||
### Совместимость
|
||||
|
||||
| Мод | Статус |
|
||||
|-----|--------|
|
||||
| Sodium | ✅ Требуется |
|
||||
| Iris | ✅ Опционально — шейдерпаки |
|
||||
| ImmediatelyFast | ✅ Опционально — производительность |
|
||||
| Entity Culling | ✅ Опционально — производительность |
|
||||
| Xaero's Minimap | ✅ Опционально — интеграция waypoint |
|
||||
| Xaero's World Map | ✅ Опционально — интеграция waypoint |
|
||||
| ViaFabricPlus | ✅ Опционально — протокол |
|
||||
|
||||
### Зависимости
|
||||
|
||||
- **Обязательные:** Fabric Loader 0.19.3+, Fabric API, Sodium, Java 25+
|
||||
- **Опциональные:** Iris, ImmediatelyFast, ViaFabricPlus, Entity Culling, Xaero's Minimap, Xaero's World Map
|
||||
|
||||
### Установка
|
||||
|
||||
1. Скачайте jar из [Releases](../../releases)
|
||||
2. Положите в папку `mods/`
|
||||
3. Перезапустите игру
|
||||
|
||||
---
|
||||
|
||||
## Development
|
||||
|
||||
### Building
|
||||
|
||||
```bash
|
||||
./gradlew build
|
||||
```
|
||||
|
||||
### Docs
|
||||
|
||||
- [Development guide](DEVELOPMENT.md) — project rules, how to add modules/HUD/events/config
|
||||
|
||||
### License
|
||||
|
||||
GNU General Public License v3.0. See [LICENSE](LICENSE).
|
||||
|
||||
---
|
||||
|
||||
## TODO
|
||||
|
||||
План разработки и актуальный статус ведутся в [TODO.md](TODO.md).
|
||||
|
||||
[loki5512344]: https://github.com/loki5512344
|
||||
529
mod/TODO.md
Normal file
529
mod/TODO.md
Normal file
|
|
@ -0,0 +1,529 @@
|
|||
# LoVisual Mod (combatant-client-26.2) — план переписи
|
||||
|
||||
Мод — форк Combatant Client, переписываем под LoVisual.
|
||||
|
||||
## Правила (ОБЯЗАТЕЛЬНЫЕ, нарушение = откат)
|
||||
- **KISS / DRY / SOLID** — простая структура, без оверинжиниринга
|
||||
- **Макс. 200 строк на файл** (было >1500) — превышение = разбить на модули
|
||||
- **Макс. 4 файла на папку** — больше = новая подпапка по смыслу
|
||||
- **Публичный API можно менять свободно** (решение владельца 2026-09-05):
|
||||
KISS важнее обратной совместимости; при рефакторинге разрешено менять
|
||||
сигнатуры, удалять делегирование и мёртвый код, обновляя вызывающих
|
||||
- **Коммиты — на английском** (решение 2026-09-23, действует с этого момента
|
||||
вперёд; более старые коммиты на русском не переписываем)
|
||||
- **Никакого статика** — `Minecraft.getInstance()` только лениво, никогда в поле
|
||||
- **Никаких this-escape** — конструктор не публикует `this`
|
||||
- **Никаких мёртвых миксинов** — миксин только если реально нужен; `cancellable=true` только при реальном cancel
|
||||
- **Без пустышек** — файл без реализации не создаётся
|
||||
- **Каждый этап компилируется** — `./gradlew build` перед переходом к следующему
|
||||
- **Тесты обязательны** для новых модулей (JUnit)
|
||||
|
||||
---
|
||||
|
||||
## СТАТУС ПРОБЛЕМ (что вижу сейчас)
|
||||
|
||||
### 1. Ребрендинг не закончен (пункт 2)
|
||||
- 288 файлов / **1464 упоминания** `combatant` в main-коде
|
||||
- Классы: `CombatantRenderSystem`, `CombatantRenderEngineBootstrap`, `CombatantRenderPipelines`, `CombatantVulkanBackend`, `CombatantFrameGraph`, `CombatantTerrainVertex` и др.
|
||||
- Заголовки файлов: «This file is part of the Combatant Client distribution» / копирайт изначального автора
|
||||
|
||||
### 2. Файлы-гиганты (пункт 3) — 12 файлов > 1500 строк
|
||||
| Файл | Строк |
|
||||
|------|-------|
|
||||
| render/engine/renderer/Renderer2D.java | 3379 |
|
||||
| features/gui/chat/BetterChatRenderer.java | 2870 |
|
||||
| features/gui/clickgui/settings/UnifiedSettingRenderer.java | 2798 |
|
||||
| features/module/modules/player/Scaffold.java | 2416 |
|
||||
| features/module/modules/combat/AttributeSwap.java | 1922 |
|
||||
| features/gui/clickgui/ClickGuiRenderer.java | 1900 |
|
||||
| features/module/modules/visuals/NameTags.java | 1791 |
|
||||
| features/module/modules/combat/ElytraTarget.java | 1711 |
|
||||
| features/gui/hud/draggable/impl/TargetHud.java | 1687 |
|
||||
| features/module/modules/visuals/ESP.java | 1520 |
|
||||
| features/module/modules/combat/AutoCrystal.java | 1516 |
|
||||
| features/gui/hud/nondraggable/impl/CustomBar.java | 1496 |
|
||||
|
||||
### 3. Runtime / JarReplacement (пункт 4)
|
||||
- `runtime/` (ClientRuntime, RuntimeGate, ClientRuntimeState, SOFT_PANIC/JAR_REPLACEMENT_PANIC, shutdown/resume-участники)
|
||||
- `runtime/loader/` (JarReplacementCoordinator, LoaderBridge, PanicOnlyJarReplacementCoordinator)
|
||||
- **Моё предложение: выкинуть.** Живая замена jar в памяти — источник classloader-утечек, хрупкая, для клиента не нужна (обновление делает лаунчер). Заменить на простой Lifecycle.
|
||||
|
||||
### 4. Security (пункт 7)
|
||||
- `features/security/BackdoorProtection` — на деле защита от SSRF/translate-инъекций (порт ExploitPreventer, MIT). Полезное, но `enum`-синглтон со статикой.
|
||||
- `features/relations/StaffTracker` + `StaffHeuristicsMatcher` — детект «стафа» по эвристикам TAB. Сомнительно, решить оставить/выкинуть.
|
||||
|
||||
### 5. Тесты (пункт 6)
|
||||
- 5 тестов на ~213k строк. Добавлять по мере переписи модулей.
|
||||
|
||||
---
|
||||
|
||||
## Фаза 1: Ребрендинг (пункт 2)
|
||||
- [x] **Восстановлен `config/`-пакет** (55+3 файла) из `ref/zip/combatant-client-26.2 (1).zip` — он отсутствовал в форке, без него проект не собирался. Переименован `combatant.client.config` → `dev.loki.lovisual.config`. `compileJava` ✓
|
||||
- [x] Заменить `combatant` → `lovisual` в main-коде (1464 вхождения, 288 файлов)
|
||||
- [x] Переименовать классы `Combatant*` → `LoVisual*` (23 шт., включая `IrisCombatantFrameHooks` → `IrisLoVisualFrameHooks`)
|
||||
- [x] Заголовки файлов → LoVisual, пересобрать копирайты (GPLv3 форка)
|
||||
- [x] Проверить `fabric.mod.json` / `lovisual.mixins.json` на остатки
|
||||
- [x] Проверить строки/сообщения/логи на «combatant»
|
||||
- [x] JNI-имена в native: `Java_combatant_client_` → `Java_dev_loki_lovisual_` (34 шт.) + FindClass-пути
|
||||
|
||||
### Проверка: `rg -i combatant src` → 0 ✓, `./gradlew build` ✓ (1406 файлов изменено)
|
||||
|
||||
## Фаза 2: Выкинуть Runtime/JarReplacement (пункт 4)
|
||||
> **Вместе с рантаймом удалить и модуль Panic** (`features/module/modules/misc/Panic.java`),
|
||||
> интерфейс `RuntimeControlModule`, команду `RuntimeCommand` и все ветки на них
|
||||
> в `ModuleManager`/`Module`. Panic — единственная реализация `RuntimeControlModule`,
|
||||
> без него они становятся мёртвым кодом.
|
||||
- [x] Удалить `runtime/` и `runtime/loader/` (14 файлов)
|
||||
- [x] Удалить `Panic.java` + `RuntimeControlModule.java` + `RuntimeCommand.java`
|
||||
- [x] Убрать ветки `instanceof RuntimeControlModule` и `tickRuntimeControllers()` из ModuleManager/Module
|
||||
- [x] Убрать `RuntimeGate` из точек входа (LoVisual.java, модули, рендер) — заменён на `Lifecycle`
|
||||
- [x] Заменить на простой Lifecycle-класс (`dev.loki.lovisual.Lifecycle`: INIT → ACTIVE → SHUTDOWN, гейты `canRunRender/Hud/ShaderBridge` + `RenderResourceReadiness`)
|
||||
- [x] Panic-фичи удалены; `ModuleManager.disableAll()` оставлен как простая утилита
|
||||
- [x] Мёртвые cleanup-методы удалены (`shutdownForRuntime`, `clearRuntimeReferences`, `VanillaChatRuntimeCleanup`, i18n-ключи panic/runtime)
|
||||
|
||||
### Проверка: `./gradlew build` ✓, тесты ✓ (13), `rg runtime-подсистема` → 0
|
||||
|
||||
## Фаза 3: Разбивка файлов-гигантов (пункт 3) — ЗАВЕРШЕНА
|
||||
> Стратегия: публичный фасад исключён из лимита ≤200 (делегирует ~все публичные методы),
|
||||
> вся логика вынесена в package-private final-хелперы в том же пакете (плоско),
|
||||
> ≤200 строк каждый. 0 вызывающих файлов изменено. AttributeSwap/Scaffold/ElytraTarget/
|
||||
> AutoCrystal удалены в Фазе 3.5 — их разбивать не нужно.
|
||||
- [x] Renderer2D (3379) → фасад 2150 + 14 хелперов (Blur, Chamfered, Circles, Connectors,
|
||||
Items, Lines, LiquidGlass, Orbiz, Polygons, Rects, RectsExtra, RectsGlow, SmokeFill, Textures)
|
||||
- [x] BetterChatRenderer (2870) → фасад 210 + 21 хелпер (LayoutEngine, Viewport, FrameRenderer,
|
||||
MessageRenderer, GlyphRenderer, InputRenderer, Suggestion*, InputHandler, MouseClick,
|
||||
ContextMenu, Tooltip, Draw/Font/EditBox/Segment/CommandMerge + 3 model-файла)
|
||||
- [x] UnifiedSettingRenderer (2798) → фасад 208 + 24 хелпера (по типам настроек + цвет-редактор
|
||||
из 9 классов: Renderer, SquareRenderer, PresetRenderer/Handler, HexInput/State, Drag, Layout, Math)
|
||||
- [x] ClickGuiRenderer (1887) → фасад 542 + 15 хелперов (Input, Keyboard, RenderEngine, Lifecycle,
|
||||
Screen, TextBatch, DrawHelpers, KeyBind, Editor, PickerIcon, TopLayer, TabBar, TabState + Model + Fonts)
|
||||
- [x] NameTags (1791) → фасад 438 + 11 хелперов (Renderer, Plate, LayoutEngine, Face, Equipment,
|
||||
Opponent, Effects, LabelBuilder, EnchantFormatter, Cache + Model)
|
||||
- [x] TargetHud (1655) → фасад 340 + 11 хелперов (Renderer, TargetResolver, Panel, Face, Content,
|
||||
Text, Arc, Equipment, Effects, Formatter + Model)
|
||||
- [x] ESP (1538) → фасад 269 + 11 хелперов (EntityCollector, ShaderRenderer/Mask/Color, 2D/3D,
|
||||
SearchOverlay, Outline, MeshBuilder, ColorUtil + Model)
|
||||
- [x] CustomBar (1495) → фасад 426 + 11 хелперов (XpBar, JumpBar, Locator*×7, Resolver + Model)
|
||||
|
||||
### Проверка: после каждого файла `./gradlew build` ✓; хелперы ≤200, фасады исключены;
|
||||
### 0 вызывающих файлов изменено во всей Фазе 3
|
||||
|
||||
### Долг (файлы >200 вне списка гигантов, в т.ч. новые фасады):
|
||||
### Renderer3D 433, Module 1181, LoVisualRenderPipelines 1329, DraggableHudElementRegistry 1449,
|
||||
### Predictions 1363, DynamicIsland 1255, CustomHealthBar 412, CustomHotbar 547, HudNotifier 1116,
|
||||
### Triangulator 1102, BetterButtons 1033, Themes 1012, SvgMeshBackend 1014, UiPrimitiveRenderer 1042,
|
||||
### BetterTooltips 948, CustomTabList 829, InventorySwap 1009, ModuleManager 521, LoVisual 441,
|
||||
### а также многие HUD/module/rendering-файлы 200–800 строк. Разбирать по желанию.
|
||||
|
||||
## Фаза 3.5: Удаление читерских модулей (легит-направление)
|
||||
> Пользователь решил: LoVisual — легитное приложение. Все читерские модули удаляются.
|
||||
- [x] combat: удалены AttributeSwap, AutoAnchor, AutoAttack, AutoBed, AutoBow, AutoCrystal, Backtrack,
|
||||
Criticals, ElytraTarget, Hitbox, KillAura, KTLeave, MaceKill. **Оставлены:** ProjectilePuncher,
|
||||
PvpCooldowns, Reach, RubberHand, SpearAssist, TPSSync
|
||||
- [x] movement: удалены ВСЕ модули (AirJump, AutoDodge, ElytraFly, ElytraHelper, Flight, Freeze,
|
||||
InventoryMove, NoFall, NoPush, NoStun, Parkour, Phase, ReverseStep, SafeWalk, Speed, Sprint,
|
||||
Step, Strafe, SuperFirework, TargetStrafe, Timer, Velocity, WindJump) — 22 файла
|
||||
- [x] player: удалены AirPlace, AutoArmor, AutoEat, AutoTotem, Scaffold, XCarry.
|
||||
**Оставлены:** AutoTool, ClickPearl, FakeLag, NoDelay, NoInteract, ShitDropper
|
||||
- [x] Осиротевшие хелпер-пакеты: удалены `combat/autocrystal/` (17), `combat/autobed/` (9),
|
||||
`combat/autoanchor/` (9), `util/block/scaffold/` (10), `BlockPlacer` + тест ScaffoldPlacementGateTest
|
||||
- [x] Enum-заглушки: `KillAura.RaycastMode/RotationTiming/AngleSmoothMode` → локальные enum в
|
||||
ProjectilePuncher/Reach; `Criticals.SelectionMode` → удалено; `Hitbox`-зависимость убрана из ESP
|
||||
- [x] ESP переписан под легит: новые настройки `only_visible` (LOS-луч от камеры), `skip_invisible`,
|
||||
`only_armor` (без брони не подсвечивать) — по умолчанию `true`, только для игроков
|
||||
|
||||
### Проверка: `./gradlew build` ✓, тесты ✓ (13), остатки только в комментариях/строках
|
||||
|
||||
## Фаза 4: Security (пункт 7)
|
||||
- [x] BackdoorProtection: убрать `enum`-синглтон, сделать инстансный сервис, ленивый `Minecraft.getInstance()`
|
||||
- [x] Решить судьбу StaffTracker/StaffHeuristics — согласовать и выкинуть или переписать
|
||||
(решение: StaffHeuristics удалён, StaffTracker+StaffData оставлены, переведены на INSTANCE-паттерн)
|
||||
- [x] Покрыть логику фильтров тестами (BackdoorProtectionTest, 11 тестов)
|
||||
|
||||
## Фаза 5: Модули — нормализация под правила
|
||||
- [x] Прочесать все 131 модуль: убрать `static final Minecraft` в полях (6 шт. уже найдено)
|
||||
(LegacyHudNotifier, ScissorFunction, ShitDropper, ProtocolUtil, CooldownRender, ClickGuiRenderer.MC
|
||||
+ 7 файлов-потребителей ClickGui-пакета — всё переведено на ленивый `Minecraft.getInstance()`)
|
||||
- [x] Проверить модули на `System.currentTimeMillis()` → заменить на игровое время
|
||||
(16 файлов модулей → новый `util/time/GameClock.millis()`, откат на стенное время вне мира)
|
||||
- [ ] Разнести addon/events/mixininterface по смыслу — ОТЛОЖЕНО: blast-radius 54/41/88 файлов-импортёров,
|
||||
чистый import-churn без функциональной ценности; делать только отдельным скриптовым проходом
|
||||
|
||||
## Фаза 6: Тесты (пункт 6)
|
||||
- [x] Юнит-тесты: EventBus (12), конфиг (values: NumberValue/Boolean/String/Set/ItemIdSet/BooleanMap,
|
||||
ModeValue, EnumValue, RGB/RGBA color; profile: DiffEngine, ValueCodec),
|
||||
утилиты (LegacyTextUtil — 12). Игровые классы без моков: тесты только на чистую логику.
|
||||
- [x] По мере переписи модулей — тест на каждый (Текущий итог: 292 теста, все зелёные)
|
||||
|
||||
## Фаза 7: QoL-модули из Delta (легит) — ПЛАН, обсуждаем
|
||||
> Референс: `ref/delta-26.2-main` (чит-клиент, код обфусцирован — берём только идеи,
|
||||
> переписываем под наши правила; у Delta 114 модулей, у нас 63).
|
||||
> Уже перенесено: SeeInvisibles→InvisESP, HandsShader→Chams/Noise, AtmoDawnFog,
|
||||
> ShulkerPreview, Animations, ItemPhysic (из WorldTweaks), HoldMyItems (фикс ordinal-бага,
|
||||
> математика в EaseCurves). Реф-исходники: ref/hmi-src, ref/soupvisuals-src.
|
||||
|
||||
### Решения по обсуждению (2026-09-05)
|
||||
- [x] Wasted — НЕ делаем
|
||||
- [x] TapeMouse — делаем (пользователь: AFK-фермы, не чит-софт)
|
||||
- [x] DeathCoords — делаем
|
||||
- [x] ItemScroller / Arrows — НЕ делаем
|
||||
- [x] ColorPlus ≈ наш PostFX — PostFX восстановлен и починен (дефолтный пресет был near-identity → добавлен Cinematic + тесты)
|
||||
- [x] Правило папок: максимум 4 файла (было 3)
|
||||
|
||||
### Перенос (список пользователя)
|
||||
- [x] **StreamerMode** (misc) — маскирует ники-подобные токены и названия серверов в чате
|
||||
(общая точка NameProtect: ChatComponentMixin.addMessage), скины заменяются на
|
||||
стандартные (AbstractClientPlayerMixin.getSkin). Чистая логика — `util/text/NameMasker`
|
||||
(тест NameMaskerTest).
|
||||
- [x] **LockSlot** (player, ~36) — запрет выброса из выбранных слотов 1–9 (анти-случайный Q),
|
||||
опция «только в PVP», предупреждение в чат. Точка: перехват drop-пакета.
|
||||
- [x] **AutoRespawn** (player, ~28) — авто-возрождение после смерти (tick на death screen).
|
||||
- [x] **AutoLeave** (player) — выход по триггерам: низкое ХП, N игроков в радиусе
|
||||
(друзья игнорируются опцией), задержка + предупреждение. Выход через
|
||||
`mc.disconnect(null, false)`; чистая state-machine `LeavePolicy` (AutoLeaveTest).
|
||||
- [x] **AutoAccept** (player) — авто-ответ на ТП/клан-запросы: паттерны фраз (SetValue),
|
||||
команда ответа, «только друзья» (PlayerRelations), задержка, кулдаун ≥500мс.
|
||||
Пакетный путь: PvpChatEvent (handleSystemChat/handlePlayerChat), отправка
|
||||
`connection.sendCommand(...)`. Чистый парсер `TeleportRequestParser` (AutoAcceptTest).
|
||||
- [x] **SoundReducer** (player, ~42) — РЕШЕНО: развитие NoSound, а не новый модуль.
|
||||
Режимы Mute (старое поведение через ClientPacketListenerMixin) и Reduce —
|
||||
новая громкость 1–100% через SoundEngineMixin (@Redirect getVolume в
|
||||
SoundEngine.play). Чистая математика `NoSound.resolveScale` (NoSoundTest).
|
||||
- [x] **Wasted** (misc, ~100) — ОТМЕНЕНО (решение пользователя)
|
||||
- [x] **ThirdPerson** (player) — свободный обзор от 3-го лица по удержанию бинда (L,
|
||||
настраивается), движение игрока не поворачивается. MouseMixin.turnPlayer копит
|
||||
orbit-yaw/pitch, CameraMixin.update (TAIL) ставит камеру за игрока по орбите
|
||||
(+ cull-frustum). Орбиты сбрасываются, когда бинд отпущен.
|
||||
- [x] **UseTracker** (player) — уведомления: мои тотемы (N осталось), тотемы других,
|
||||
эффекты оппонентов (группа: invisibility/speed/strength/regeneration/fire_res/weakness).
|
||||
Пакетный путь: ClientboundEntityEventPacket (event 35) + ClientboundUpdateMobEffectPacket.
|
||||
Тест UseTrackerTest.
|
||||
- [x] **NoServerPack** (misc) — авто-отклонение принудительного серверного ресурспака
|
||||
(спрашивать/отклонять всегда). Точка: ClientCommonPacketListenerImplMixin.
|
||||
- [x] **NoFriendDamage** (combat, ~19) — отмена атаки, если цель — друг (PlayerRelations).
|
||||
- [x] **TapeMouse** — ОСТАВЛЕН (решение владельца 2026-09-08): автоклик по таймеру
|
||||
(Attack/Use) для AFK-ферм, интервал, опция «только при зажатии». Считаем
|
||||
допустимым исключением из Фазы 3.5 по явному решению владельца.
|
||||
|
||||
### Кандидаты из отчёта (не в списке пользователя — обсудить)
|
||||
- [x] **DeathCoords** (~27) — координаты последней смерти в чат. Дёшево, полезно.
|
||||
- [x] **ItemScroller** (misc) — shift-перекладка предметов колёсиком в контейнерах:
|
||||
QUICK_MOVE клик по слоту под курсором, иначе слот хотбара (опция).
|
||||
Точка: AbstractContainerScreenMixin.mouseScrolled; чистая логика
|
||||
`ScrollMovePolicy` (ScrollMovePolicyTest).
|
||||
- [x] **Arrows / off-screen индикаторы** — ОТМЕНЕНО (решение владельца 2026-09-08).
|
||||
|
||||
### Проверка после каждого модуля: `./gradlew build` ✓, тесты на чистую логику ✓
|
||||
|
||||
## Фаза 7.5: Команды — префикс % + автокомплит
|
||||
- [x] Префикс команд сменён `@` → **`%`** (старый `@` принимается как legacy).
|
||||
Источник истины — `features/command/CommandPrefix` (CHAR/STRING/isCommandLike/strip);
|
||||
вызовы обновлены: CommandManager.handle/suggest, ScreenMixin (RunCommand),
|
||||
BetterChat (TabHandler, SuggestionState, SuggestionRenderer, ContextMenuHandler),
|
||||
usage-строки и RunCommand-ссылки всех команд (help/modules и др.).
|
||||
- [x] Аргументный автокомплит дополнен usage-подсказками: если `suggest()` команды
|
||||
не дал вариантов на позиции — показывается подсказка вида `%toggle <module>`
|
||||
(`features/command/UsageHints`, парсит `<...>`/`[...]` из usage-строки).
|
||||
Существующий UI автокомплита BetterChat (стрелки/Tab/клик) работает как раньше.
|
||||
|
||||
### Проверка: `./gradlew build` ✓, `./gradlew test` ✓ (CommandPrefixTest, UsageHintsTest,
|
||||
### CommandDiscoveryTest обновлён)
|
||||
|
||||
## Фаза 8: Структура «как у Delta» (маленькие файлы) — ПЛАН
|
||||
> Правило ≤200 уже есть (Фаза 1–3), но долг: ~240 файлов >200 строк.
|
||||
> У Delta файлы компактные и слои разделены: api / client(features, ui, utils, processors) /
|
||||
> inject(accessors, invokers, mixin). Наша пакетная структура сопоставима — проблема в размере файлов.
|
||||
|
||||
- [ ] Топ-гигантов к разбивке (после Фазы 3): LoVisualRenderPipelines 1527,
|
||||
DraggableHudElementRegistry 1449, Predictions 1363, DynamicIsland 1254, Module 1181,
|
||||
HudNotifier 1116, AltManager 1115, Triangulator 1102, TargetESP 1061, UiPrimitiveRenderer 1042
|
||||
- [ ] Стратегия: как в Фазе 3 — фасад + package-private хелперы ≤200, 0 изменений вызывающих,
|
||||
`./gradlew build` после каждого; по мере касания файлов в Фазе 7 — разбивать на ходу
|
||||
- [ ] Facades >200 (Renderer2D 2150 и т.п.) — оставить как есть (исключение по правилам)
|
||||
- [ ] Не смешивать с Фазой 7: разбивка структуры — отдельными проходами, иначе diff-каша
|
||||
|
||||
### Проверка: `./gradlew test` зелёный
|
||||
|
||||
## Фаза 8.5: Аудит структуры (правила ≤200 строк / ≤4 файла) — ПОЛНЫЙ СПИСОК НА РЕФАКТОРИНГ
|
||||
> Снимок 2026-09-09 (`src/main/java`, 1459 файлов / 197k строк).
|
||||
> **Гейт перед Фазой 9.2 (Optimize)**: движковые файлы, которые Optimize будет трогать,
|
||||
> должны быть разбиты заранее. 9.1 (мёртвые грузы) от этого НЕ зависит — идёт своим порядком.
|
||||
> Стратегия та же, что Фаза 3/8: фасад + package-private хелперы ≤200, 0 правок вызывающих,
|
||||
> билд после каждого файла. Фасад-исключение (Renderer2D) — см. оговорку ниже.
|
||||
|
||||
### Итоговая картина
|
||||
- **Файлы >200 строк: 244 шт.** → >800 строк: 26 | 400–800: 78 | 201–400: 140
|
||||
- **Папки >4 файлов: 86 шт.**
|
||||
- Разбивка больших файлов по зонам: features/gui — 73 | render/engine — 54 |
|
||||
features/module — 35 | util — ~35 | mixins — 3 | config — ~6 | прочее — остальное
|
||||
|
||||
### 8.5.1 Папки >4 файлов — топ должников (разбить на подпапки по смыслу)
|
||||
- [x] `mixins/` — 108 файлов → leaf-пакеты (entity/blaze3d/input/world/network/gui/hud/render),
|
||||
mixins.json перегенерирован, FQN-строки LoVisualMixinPlugin обновлены. Коммиты 94d5af7, 3c76817.
|
||||
- [x] `mixins/accessors/` — 45 → 12 групп (entity/renderer/world/state/packet/inventory/...). Коммит 3c76817.
|
||||
Также разбиты iris/sodium/security на подпакеты.
|
||||
- [x] `features/module/modules/visuals/` — 67 → esp/nametags/hats/effects/weather/scene/camera/
|
||||
player/items/fx + lyrics/lrc. Конфиг-id НЕ менялись (проверено). Коммит 073ac26.
|
||||
- [x] `features/gui/clickgui/settings/` — 51 → core/bool/mode/slider/text/text-list/group/bind/
|
||||
color(+render/preset/hex)/i18n/render/skin/owner/cooldown/util. Коммит 9db1fec.
|
||||
- [x] `features/gui/hud/draggable/impl/` — 40 → stats/metrics/status/combat/panels/targethud(+/render,
|
||||
render/parts)/scripted + hudnotifier/model, targethud-модель свёрнута в класс с record-ами. Коммит 6b89e40.
|
||||
- [x] `events/impl/` — 32 → input/movement/world/network/entity/pvp/render/player;
|
||||
events/ верхний уровень: core(Event,EventBus,Events) + meta(EventHandler,UsedImplicitly).
|
||||
- [x] `features/gui/chat/` — 31 → `render/`, `suggestions/`, `menu/`, `model/`.
|
||||
- [x] `render/engine/uniform/impl/` — 28 → по потребителям (`uniform/impl/pipeline/`, `uniform/impl/effects/`).
|
||||
- [x] `render/engine/renderer/ui/` — 28: верхний уровень разнести по уже существующим
|
||||
`draw/`, `runtime/`, добавить `blur/`, `batches/`.
|
||||
- [x] `render/engine/text/` — 24 и `text/backend/` — 12 → `text/` разбить на `text/render/`,
|
||||
`text/layout/`, `text/msdf/`.
|
||||
- [x] `render/engine/renderer/ui/runtime/script/` — 23, `ui/draw/` — 23 → внутри по 4-файловым кластерам.
|
||||
- [x] `features/gui/hud/nondraggable/impl/` — 20 (+`impl/tab/`) → `impl/overlays/`, `impl/tablist/`.
|
||||
- [x] `features/gui/clickgui/` — 20 на верхнем уровне → всё в существующие `layout/`, `sections/`,
|
||||
`picker/`, `protocol/`, `util/`.
|
||||
- [x] `render/engine/command/` — 17, `render/helpers/` — 16, `features/command/impl/` — 16,
|
||||
`config/values/` — 16 → по 2-3 подпапки (типам: `values/numeric/`, `values/color/`…).
|
||||
- [x] `render/engine/profiler/` — 14, `modules/player/` — 14, `features/gui/hud/` — 14,
|
||||
`addon/` — 14 — средние: раскидать при касании.
|
||||
- [x] Хвост (5–13 файлов, ~55 папок): `util/pvp` 13, `util/projectile` 13, `render/iris` 13,
|
||||
`config/profile` 13, `features/module/misc` 12, `features/module` 12, `config` 12 и т.д. —
|
||||
ЗАКРЫТ выделенным проходом (коммиты 8846d53…303b17e, волна 8.5.1 завершена).
|
||||
Снимок после волны: 0 папок >4 файлов в `src/main/java` (скан 2026-09-10).
|
||||
Замечания: command-discovery рекурсивный (ClassGraph acceptPackages), конфиг-id
|
||||
и ключи i18n не менялись; package-private члены, ставшие кросс-пакетными,
|
||||
расширены до public/protected; svgMsdfTool-импорты починены после split svg.
|
||||
|
||||
### 8.5.2 Файлы-гиганты >600 строк — приоритетная очередь разбивки (53 файла)
|
||||
> Формат: файл (строк) → идея разбивки. Порядок сверху вниз. Facade-оговорка:
|
||||
> Renderer2D остаётся фасадом-делегатом (правило Фазы 8), но его вспомогательные
|
||||
> классы (kawase/blur/glass) — вынести из OrderedUiBatcher (935) в `ui/blur/`.
|
||||
- [ ] Renderer2D 2166 — ФАСАД (исключение по правилу Фазы 8): оставить делегирование,
|
||||
но блоки >200 строк переносить в package-private хелперы в `renderer/renderer2d/`
|
||||
(частично уже есть Rects2D/Strokes2D)
|
||||
- [x] LoVisualAltManagerScreen 1113 → ГОТОВО (2026-09-10): 11 файлов `mainmenu/alt/`
|
||||
(Screen 132, Controller 200, Ops 59, Anims 108 + auth/ 171 + render/ 157/156/139/100
|
||||
+ render/cards/ 178/166), все ≤200, build+test ✓
|
||||
- [x] UiPrimitiveRenderer 1053 → ГОТОВО (2026-09-10): фасад 188 (коннекторы) +
|
||||
render/primitive/ 4 (Context 153, Props 158, Painter 145, GlowPainter 147) +
|
||||
render/rect/ 2 (RectPainter 150, CornerPainter 150), build+test ✓
|
||||
- [x] BetterButtons 1032 → ГОТОВО 7e86f8d: 388 + 7×≤200 (state/hover/parallax/queue/render) — extraction+tooltip+render → `hud/nondraggable/impl/buttons/`
|
||||
- [x] InventorySwap 1031 → УДАЛЁН 5acafc8: чит-инфра, заменён ShitEsp + хотбар-only — по стратегиям свапа; чистая логика отдельными классами с тестами
|
||||
- [x] SvgMeshBackend 1014 → ГОТОВО c11ebe3/aafe7de: 1020→267 + Parser181/Geometry173/Texture223/Render35/Cache25 — parser/triangulate/cache разнести
|
||||
- [x] Themes 1012 → ГОТОВО e51a610: 1012→562 + 3×163 пресета — реестр тем в `theme/presets/` (по 4 темы/файл), дефолты отдельно
|
||||
- [x] WorldParticles 991 → ГОТОВО 1d757a6+5a463d7e: 999→821→260 (фасад) + ambient/render/ 3×≤182
|
||||
(Batches/Bubble/Funnel) + ambient/particle/ 197 + geometry/ доработаны (offset/multiplyAlpha/STACKS) —
|
||||
типы частиц в `visuals/effects/ambient/`
|
||||
- [x] Module 989 → ГОТОВО c8da336: 1031→139 + 4×≤134 (ext/) — базовый класс: settings-механику вынести в `module/ext/` (осторожно, общий предок!)
|
||||
- [ ] LoVisualAddonManagerScreen 989 — как AltManager — как AltManager
|
||||
- [x] Chams 976 → ГОТОВО 78b5335: 985→129 + 4×≤195 — режимы рендера в подклассы-политики (фасад модуля тонкий)
|
||||
- [x] ClickGuiPickerState 962 → ГОТОВО 234f0d9: 970→166 + 4×≤140; CombatProtocolHeuristicsEditorState 932→79 +4×≤192 03ae4a6 — state/actions хелперы
|
||||
- [x] ModulesMenuScreen 960 → ГОТОВО 234f0d9: 966→145 + 4×≤178 — рендер категорий отдельно от состояния
|
||||
- [x] UiMeshGeometry 954 → ГОТОВО sub-agent: 956→99 + 4×≤135 — по примитивам геометрии
|
||||
- [x] BetterTooltips 953 → ГОТОВО 0b8ea41: 960→181 +4×≤199; OrderedUiBatcher 935 → ГОТОВО 6e0bf7f: 944→188 (→ batches + blur), Scoreboard 924,
|
||||
Rain 893 → ГОТОВО sub-agent: 903→159 +4×≤162; CompactHudStatModel 893 → ГОТОВО 8979140: 894→125 +4×≤175; TazikHat 859 ✓ ✓ закрыт портированием в
|
||||
Cosmetics built-in (2026-09-11, см. Фазу 7),
|
||||
ShaderPatchCompiler 843 → ГОТОВО 2b55fbc: 843→66+4×≤174; OnlineRelationPlayerPickerComponent 837→74+4×≤192 17fc665; CustomTabList 830 → ГОТОВО 9e9b71d: 834→136+4×≤166,
|
||||
GameRendererMixin 830 → ГОТОВО f45f46e: 830→344 (только хуки+Host/BobInvoker) +
|
||||
mixins/render/main/handlers/ 4×≤200 (ProjectionHelper/WorldEngine/WorldPost/WorldDebug), Predictions 805 → ГОТОВО (см. хвост)
|
||||
- [x] Хвост 400–800: ЧАСТИЧНО — ConfigProfilesComponent 799→125 d95bfec, HitEffect 770→120 5e1ce05, PlayerMovementSimulation 757→157 4b253d1, ProjectilePuncher 747→104 fba4f7d, MediaPlayer 739→174 8ce3927, Crosshair 737→143 4cf0970, Itemizer 699→193/Cooldowns 707→151 11245ac, Potions 617→176 2e4912a, Admins 702→118 f18cb96, Keybinds 611→157 cc18feb, ModuleList 499→181 52327dc, Radar 392→161 f580373, Fps 309→168 5df2cc0, Memory 304→151 de7cc2b, Tps 339→154 e167f0c, Ping 309→145 15d04cb, SpeedBps 334→156 b78a638, GameTime 314→150 922d3bc, SystemTime 300→136 3cb6e40, Coordinates 337→174 9412982, Armor 324→162 932639d, Inventory 476→153 f4124f4, BlockHighlight 692→271+4×≤200 9f76e5a5 (scene/highlight/), см. /tmp-снимок в истории команд: ConfigProfilesComponent 791,
|
||||
HitEffect 770, PlayerMovementSimulation 755, ProjectilePuncher 746, MediaPlayer 739,
|
||||
Crosshair 737, MeshBuilder 729, SettingsPanelComponent 703, Admins 702, Cooldowns 701,
|
||||
Itemizer 699, LocalPlayerMixin 687, Trails 681, ItemBatchRenderer 673,
|
||||
CosmeticModel 671, MenuScreen 667, GlStencilFramebufferSupport 663, ConfigSerializer 663,
|
||||
DynamicIsland 661, ReimaginedVisual 660, RelationsComponent 659, UiStyle 640, Potions 617,
|
||||
ModuleComponent 612, MsdfFont 606, Keybinds 603, MediaSessionService 594 и др.)
|
||||
|
||||
### 8.5.3 201–400 строк (~140 файлов) — проход «касаться = чинить»
|
||||
- [ ] Не делать отдельным марафоном: при правке файла по другой фазе — первым коммитом
|
||||
разбивка на ≤200, вторым — целевое изменение (иначе diff-каша, правило Фазы 8)
|
||||
|
||||
### 8.5.4 Порядок и критерии готовности
|
||||
- [x] Очередь: 8.5.1 крупные папки (mixins, visuals, clickgui/settings, hud impl) →
|
||||
8.5.2 гиганты >800 → далее по убыванию. Каждая папка/файл = отдельный коммит.
|
||||
→ 8.5.1 ЗАВЕРШЕНА (2026-09-10): 0 папок >4 файлов.
|
||||
- [ ] После каждого шага: `./gradlew build` ✓, `./gradlew test` ✓; конфиг-id модулей и
|
||||
ключи сеттингов НЕ ломаем (совместимость .lvcfg); скрипты-переименования пакетов
|
||||
не трогают string-literals id — проверять grep'ом после moves.
|
||||
- [ ] Критерий закрытия для старта 9.2: ноль файлов >200 в путях, которые трогает Optimize
|
||||
(Renderer2D-секции blur/glass, OrderedUiBatcher, HUD-имплементации bgEffect,
|
||||
MsdfFont/CustomTextRenderer), и ноль папок >4 в этих же пакетах. Полный ноль по всем
|
||||
244/86 — долгий хвост, 9.2 им не блокируется.
|
||||
- [ ] Обновить этот раздел при подходе к волне (отмечать [x], доснимать счётчики).
|
||||
|
||||
## Фаза 9: Оптимизация FPS (аудит 2026-09-09) — ПЛАН
|
||||
> Диагноз: у клиента есть «налог каждый кадр», который платится даже при
|
||||
> выключенных модулях (друг: просадка FPS на чистом конфиге, Windows).
|
||||
> Решение владельца: мёртвые грузы — ЧИНИМ в коде; авто-деградации по FPS НЕ ДЕЛАЕМ;
|
||||
> вместо неё — ручной модуль **Optimize** (включил → порезали стекло/blur/тяжёлые проходы).
|
||||
|
||||
### 9.1 Мёртвые грузы (чиним в коде всегда, независимо от модулей) — приоритет
|
||||
- [x] **glGetError на каждом render pass** — ГОТОВО 2026-09-11 (коммит 137121e): гейт по clip-active || stencil-debug — `GlStencilShapeClipBackend.endRenderPass`
|
||||
(`:140`) и `beginRenderPass` (`:98/:104/:110/:124`) дёргают `checkGlErrors`
|
||||
(`:428-434`) на КАЖДЫЙ проход (миксин `CommandEncoderMixin:102-112` висит на
|
||||
submitRenderPass → это и все ванильные/Sodium проходы). `glGetError` = синк с
|
||||
Windows-драйвером, несколько мс/кадр. Фикс: проверять только если
|
||||
`mode != DISABLED || renderPassAttachmentRequired`, либо под dev-флагом;
|
||||
в релизе — no-op.
|
||||
- [x] **`lovisual$isVulkanBackend()` на каждый submitRenderPass** — ГОТОВО (c9a65b1), кэш Boolean
|
||||
(`CommandEncoderMixin:66-74`) — `getDeviceInfo().backendName().toLowerCase()`
|
||||
заново на кадр×проходы. Фикс: вычислить один раз, закэшировать boolean.
|
||||
- [x] **PreTranslucentDepth — полноэкранный depth-copy каждый кадр без нужды** — ГОТОВО (b747b47): demand-флаг requestForNextFrame()/takeRequested() у потребителей getDepthView(For), capture в vanilla- и Iris-путях по запросу (1-кадр задержка, фолбэк на live view) —
|
||||
`LevelRendererMixin:275-283` гейтится только «нет Iris». Фикс: гейт
|
||||
`needsPreTranslucentDepthCapture()` по образцу `WorldSceneDepth`
|
||||
(`LevelRendererMixin:160-218`); потребители: `PostProcessGraphResources:61`,
|
||||
`LoVisualVisuals:79`, `WorldPassCompiler:174`.
|
||||
- [x] **copyMainColor каждый кадр ДО гейта** — ГОТОВО (118eb2a): ранний return по liquidGlassBlurRequested — `UiBlurResources.captureWorldSource`
|
||||
(`:116-123`): полноэкранный color-copy делается до проверки
|
||||
`liquidGlassBlurRequested` (`:122`). Фикс: переставить — copy только когда
|
||||
blur реально запрошен.
|
||||
- [x] **Строки профайлера при выключенном профайлере** — ГОТОВО (aa55c4d): 2-arg scope()/section()/postPass(prefix,suffix) в ProfilerPhase/RenderProfiler2D/3D/RenderCostProfiler (DEV-гейт конкатенации) — конкатенации на call-site
|
||||
каждый кадр: `PostProcessGraph:59` (`"graph:" + phase`), `ModuleManager:219-221/:290`
|
||||
(`"3d:module:" + m.name()`). Фикс: ленивые supplier'ы / ранний isEnabled-check.
|
||||
- [x] **Мелочь, по ходу**: `new PoseStack`/`new Matrix4f`×2/`new Frustum`×2 в кадре
|
||||
(`GameRendererMixin:203-239/:341-347/:609-617`) — закэшить переиспользуемые копии. Frustum-часть отменена (da6525c): @Invoker("calculateFrustum") не резолвится на remapped-рантайме = краш; scratch-кэш матриц/PoseStack остался.
|
||||
|
||||
### 9.2 Модуль **Optimize** (misc) — ручной рубильник экономии
|
||||
> ⛔ ГЕЙТ: не начинать, пока не закрыта Фаза 8.5 (рефакторинг-аудитStructure ниже) —
|
||||
> Optimize трогает Renderer2D/OrderedUiBatcher/HUD-имплементации, все они >200 строк.
|
||||
> Идея владельца: один тумблер «хочу максимум FPS». НИКАКОГО автовключения по FPS.
|
||||
> Пока активен — движок и HUD работают в лёгком режиме.
|
||||
- [ ] Каркас: `modules/misc/Optimize.java` (≤200 строк, тест `OptimizeTest` на чистую логику).
|
||||
Настройки (bool, дефолт on при включении модуля):
|
||||
- `no_glass` — все glass/blur-эффекты HUD off: форсить bgEffect=None у всех
|
||||
HUD-элементов (Fps сейчас по умолчанию "Blur", `Fps:70`), сделать
|
||||
`Renderer2D.requestLiquidGlassBlur*` no-op, пропускать kawase-цепочку в
|
||||
`OrderedUiBatcher.prepareSharedBlurInternal`.
|
||||
- `lite_post` — резать тапы тяжёлых пост-проходов: MotionBlur 15→5
|
||||
(+ neighborhood 10→0), DoF 32→8 — через uniform, без переписывания шейдеров
|
||||
(альтернатива жёстче: временно деактивировать проходы — решить на реализации, KISS).
|
||||
- `lite_sky` — процедурные скайбоксы (reimagined_skybox / pulsar / thunder,
|
||||
~20 fbm-оценок на пиксель) — пропускать noise-слои.
|
||||
- `lean_hud` — off для per-frame аллокационных прибамбасов: градиенты/бегущие
|
||||
строки (`CustomTextRenderer:387` new String на глиф), анимации цифр.
|
||||
- [ ] Механизм «как движок узнаёт»: НЕ тыкать статику модуля в лоб — сделать
|
||||
`OptimizeState` (boolean + getter, обновление при enable/disable), читать через
|
||||
него в движке (паттерн уже есть: `ReimaginedVisual.needsWorldSceneDepthCapture()`).
|
||||
- [ ] Взаимодействие с 9.1: фиксы 9.1 НЕ отменяются модулем — copy/ошибки чиним всегда;
|
||||
Optimize режет только то, что имеет визуальную цену.
|
||||
- [ ] i18n en_us + ru_ru обязательно: `module.optimize.*`, `setting.optimize.*`.
|
||||
- [ ] Нотификация при первом включении (chat/HUD): что именно порезано.
|
||||
|
||||
### 9.3 Проверка
|
||||
- [ ] A/B-мерка до/после 9.1 на чистом конфиге (F3/DebugHud, пустой мир, 1080p):
|
||||
целевой эффект — минус 2 полноэкранных copy/кадр и минус N glGetError-синков
|
||||
(N = проходов за кадр).
|
||||
- [ ] `./gradlew build` после каждого пункта; `./gradlew test` зелёный.
|
||||
- [ ] Порядок: 9.1 (по одному пункту на коммит) → 9.2.
|
||||
|
||||
## Фаза 10: Заход по референсам из Downloads (2026-09-15)
|
||||
> Пользователь скинул 5 архивов, распакованы в `/tmp/lv_refs/`. Порядок выполнения —
|
||||
> сверху вниз, по одному коммиту на пункт, `./gradlew build`+`test` после каждого.
|
||||
|
||||
- [x] **TrollfaceMask — почини "не работает"** (`/tmp/lv_refs/trollface/TrollfaceMask.java`,
|
||||
референс Moonward 1.21.4). Наш модуль: `trollface/TrollfaceMask.java`.
|
||||
Причина бага: биллборд ориентировался к камере (headPos→camPos); от первого лица
|
||||
камера почти совпадает по вертикали с головой → view≈(0,1,0) → right=view×up
|
||||
вырождается в 0 → плоскость ложится горизонтально, не видна. Режимы «Друзей»/«Всех»
|
||||
брали только `TargetManager.getTarget()` (сущность под прицелом) — маска рисовалась
|
||||
максимум на одном игроке. Фикс: ориентация по `getViewVector()` цели вместо камеры,
|
||||
перебор `mc.level.players()` с фильтром по режиму (себя/friend via PlayerRelations/все).
|
||||
Коммит e7e0ff2.
|
||||
- [x] **Rain — сравнение с двумя референсами (2026-09-15, вывод: у нас уже паритет/лучше).**
|
||||
Референс 1 `/tmp/lv_refs/rainfull/` (Cataclysm client) — наш `Rain.java` (894 строки) уже
|
||||
является портом этого самого класса (Drop/Splash/Droplet/Mist, presetDensity/Wind/Mass,
|
||||
drawStreaks/Ripples/Crowns/Droplets/Mist — 1:1 совпадающие константы и формулы), ПЛЮС у нас
|
||||
уже есть их wet-surface screen-space постфх (`WetSurfaceUniforms` + шейдер
|
||||
`assets/lovisual/shaders/wet_surface.frag`, pipeline `WET_SURFACE`, реализован как
|
||||
`PostProcessPass` в самом Rain.java) — то, что в референсе вынесено в отдельный
|
||||
`WetSurfaceRenderer`. Улучшать нечего, разница только в деталях реализации пайплайна.
|
||||
Референс 2 `/tmp/lv_refs/mokriyzhir/` (`WetWorld.java`, пакет `ez.redux...`) — это ОТДЕЛЬНЫЙ
|
||||
самостоятельный модуль "Wet World" из чужого чит-клиента (Category.VISUALS), НЕ часть дождя:
|
||||
мочит поверхности всего мира по реальной погоде сервера (`world.getRainGradient`), с настройками
|
||||
Quality (Low/Medium/High/Ultra), Reflection Strength, Wet Darkening, Ripples+Speed, Rain Only,
|
||||
учитывает fog (интеграция с их модулем Fog: цвет/дистанция/яркость подмешивается в шейдер).
|
||||
У нас такого отдельного всегда-активного "мир мокрый по факту дождя" модуля нет — наш
|
||||
wet-surface жёстко завязан на модуль Rain (работает только когда сам Rain включён). Если
|
||||
захочется — можно вынести wet-surface-pass Rain.java в отдельный модуль WetWorld с привязкой
|
||||
к `mc.level.isRaining()`+`getRainLevel(tickDelta)` вместо `onlyWhenRaining` галки, плюс quality-
|
||||
пресет и fog-интеграцию. НЕ делаю сейчас — не запрошено явно, чисто идея на будущее.
|
||||
- [x] **WetWorld — сделан отдельным модулем (2026-09-15), шейдер Rain пофикшен.**
|
||||
Третий референс `/tmp/lv_refs/wetworld2/` (`ru.white...WetWorld` + `WetWorldPipeline` +
|
||||
`wet_world.vsh/fsh`) оказался технически лучшим из трёх: настоящий SSR с бинарным
|
||||
рефайнментом пересечения, dithering шага луча, реконструкция нормали по соседям в буфере
|
||||
глубины (не screen-space derivative), fbm-небо с sun specular, fog-интеграция.
|
||||
Проверка нашего `wet_surface.frag` («может кривые») подтвердила баги:
|
||||
1) `normalFromDepth` считался через `dFdx/dFdy(viewPos)` — рвётся на границах глубины,
|
||||
шумная/блочная нормаль -> дрожащий край лужи;
|
||||
2) рябь была МЁРТВЫМ КОДОМ: `vec2 perturb = vec2(dFdx(ripple), dFdy(ripple)) * 0.0;` —
|
||||
умножение на 0 полностью гасило эффект, а сама рябь добавлялась как сырое значение
|
||||
волны вместо её наклона.
|
||||
Исправлено (коммит 0986ce6): нормаль — по 4 соседям depth-буфера (как в лучшем референсе),
|
||||
рябь — аналитический градиент (разность высоты в соседних точках), добавлен bin-рефайнмент
|
||||
SSR-пересечения + dithering, небо дополнено fbm-облаками/sun specular, затемнение вынесено
|
||||
в отдельный uniform-параметр (было зашито константой 0.82). Новый модуль
|
||||
`visuals/weather/WetWorld.java`: мочит мир по факту `mc.level.getRainLevel()`, независимо
|
||||
от партиклов Rain и тумблера `wet_ground` — Quality (Low/Medium/High/Ultra
|
||||
-> шаги/дистанция/bin-рефайнмент SSR), Reflection Strength, Darkening, Ripples+Speed,
|
||||
Rain Only. Переиспользует общий `WET_SURFACE` pipeline/`WetSurfaceUniforms` (при
|
||||
одновременном включении с Rain.wet_ground эффект стекается — задокументировано в коде).
|
||||
Fog-интеграция референса НЕ перенесена (нет доступа к чужому Fog-модулю/данным тумана в
|
||||
нашем движке в этом заходе) — можно добавить отдельно, если понадобится.
|
||||
- [x] **HitEffect — интегрирован ImpactRing (2026-09-15).**
|
||||
Референс `/tmp/lv_refs/myasomaybe/ImpactRing/` — `JumpWaveRenderer`/`JumpGlowRenderer`
|
||||
используют захват сцены + собственный низкоуровневый RHI-пайплайн с SSR-варпом
|
||||
(кастомный шейдер сэмплит скопированный цветовой буфер по кольцу) — тяжеловесная техника
|
||||
не в духе нашего движка. Взята идея визуала (кольцо + вертикальная стена свечения в точке
|
||||
удара), реализована через уже существующий движок: обычные аддитивные квады через
|
||||
MeshBuilder/Renderer3D (`WORLD_COLORED_ADDITIVE` + `WORLD_COLORED_ADDITIVE_DEPTH`), без
|
||||
захвата сцены и отдельного шейдера — консистентно с уже существующими WaveEffect/HitBubble
|
||||
в том же файле. Новый `EffectMode.IMPACT` в HitEffect: настройки impact_radius/
|
||||
impact_duration/impact_glow_height, срабатывает как WAVE (по удару), рендер —
|
||||
расширяющееся кольцо (сегменты, fade к центру) + полупрозрачная вертикальная стена по
|
||||
контуру круга, затухающая вверх и во времени. Коммит 61c478e. `./gradlew build`+`test` ✓.
|
||||
- [x] **HoldMyItems — сверка с HMI.zip (2026-09-15), портирован grip.**
|
||||
Референс `/tmp/lv_refs/hmi/` (Delta HMI): обёртка обфусцированного чит-клиента над
|
||||
СТОРОННИМ jar-модом `holdmyitems-5.1.1+26.2.jar` + свои `SwingAnimations` (десяток стилей
|
||||
свинга, weapon-inspect a-la CS:GO karambit-spin, "Pretty Hands" режимы). Полный набор
|
||||
НЕ портирован — фича-крип чит-клиента, конфликтует с KISS и с правилом «без стороннего
|
||||
jar в сборке» (Delta буквально бандлит чужой мод и синхронизирует с ним настройки через
|
||||
`OriginalHmiBridge`). Взята единственная самоценная и самодостаточная идея — **grip**:
|
||||
лёгкий хват предметов с рукоятью (мечи/инструменты/трезубец/палки — см.
|
||||
`heldAlongTheFist`) наискось в кулаке вместо строго вертикального ванильного equip.
|
||||
Портировано (коммит b257fde): `HeldAlongFist` (чистый предикат по ItemTags),
|
||||
`HandPoseMath.grip(...)` (чистая функция позы, тесты gripMirrorsBySide/
|
||||
gripExtendPullsCloserAndAcrossFist), настройки `grip_enabled`+6 slider'ов в HoldMyItems
|
||||
(дефолты как у референсного пресета "HMI"), проброс ItemStack через
|
||||
HandDynamics.apply/ItemInHandRendererMixin. `./gradlew build`+`test` зелёные.
|
||||
|
||||
### Проверка после каждого пункта: `./gradlew build` ✓, `./gradlew test` ✓, TODO.md отмечен
|
||||
|
||||
## Фаза 11: Аудит attack-визуалов — sacura 1.21.4 / GodWeer-26.2 (2026-09-22)
|
||||
> Референсы распакованы в `ref/clients/sacura-1.21.4` и `ref/clients/godweer-26.2`.
|
||||
> Вывод по большинству эффектов: у нас уже полноценнее (больше режимов, единый render
|
||||
> engine с пайплайнами вместо сырого GL). Ниже — конкретные пробелы, которые реально
|
||||
> стоит доделать; всё остальное сравнённое (HitEffect, KillEffect, JumpCircles,
|
||||
> Hitboxes, ItemPhysic, ViewModel offsets) уже на уровне или выше обоих референсов.
|
||||
|
||||
- [ ] **ViewModel — `Custom` swing-режим.** sacura (`SwingAnimationsModule`) имеет режим
|
||||
"Кастомная" с explicit слайдерами угол/наклон. У нас 8 фиксированных пресетов
|
||||
(Hammer/Chop/Arc/Double/Shake/Shove/Slash/Thrust), но нет свободно настраиваемого.
|
||||
Также посмотреть на sacura-режимы "Возвращение"/"Возвращение к себе"/"Круговая" —
|
||||
возможно стоят портирования как доп. пресеты, если визуально отличаются от наших.
|
||||
- [ ] **HitEffect — опциональный distortion/glow post-process слой.** godweer
|
||||
(`HitEffectRenderer`) кроме частиц кладёт screen-space distortion+glow слайдеры.
|
||||
У нас частицы (Bubbles/Wave/Impact) есть, post-process слоя над ними нет.
|
||||
Паттерн `PostProcessPass` уже есть (см. `TotemFX`), можно переиспользовать —
|
||||
но не блокирующая, это чистый апгрейд поверх уже более богатой системы.
|
||||
- [ ] **JumpCircles — easing на появление/исчезновение.** sacura использует `EaseBackIn`
|
||||
для пружинки при спавне/затухании круга. Проверить `render/engine/math` — если
|
||||
easing-утилита уже есть, подключить к текущему fade вместо линейного.
|
||||
- [ ] **KillEffect — through-walls поведение.** godweer (`PopEffect`) имеет явный toggle
|
||||
"сквозь стены" для beam/взрыв эффектов. Проверить DepthMode у Lightning/Orthodox
|
||||
beam в нашем KillEffect — сейчас режется окклюзией или нет; если режется и это не
|
||||
специально — добавить toggle по аналогии.
|
||||
- [ ] **Trails — живое сравнение с sacura `TrailsModule`.** Не разбирался по коду в этом
|
||||
заходе (визуальный эффект, решение лучше принимать посмотрев обе стороны вживую
|
||||
в игре, а не по исходникам).
|
||||
|
||||
### Итог: ничего из sacura/GodWeer не даёт принципиально нового attack-эффекта,
|
||||
### которого нет в LoVisual — расхождение только в деталях полировки (easing-кривые,
|
||||
### доп. custom-режим свинга, возможный distortion-слой, through-walls toggle).
|
||||
466
mod/build.gradle
Normal file
466
mod/build.gradle
Normal file
|
|
@ -0,0 +1,466 @@
|
|||
plugins {
|
||||
id 'net.fabricmc.fabric-loom' version '1.17.12'
|
||||
id 'maven-publish'
|
||||
id 'pmd'
|
||||
id 'checkstyle'
|
||||
id 'com.github.spotbugs' version '6.5.11'
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven {
|
||||
url = 'https://maven.fabricmc.net/'
|
||||
}
|
||||
exclusiveContent {
|
||||
forRepository {
|
||||
maven {
|
||||
name = "Modrinth"
|
||||
url = "https://api.modrinth.com/maven"
|
||||
}
|
||||
}
|
||||
filter {
|
||||
includeGroup "maven.modrinth"
|
||||
}
|
||||
}
|
||||
maven {
|
||||
// ViaFabricPlus / ViaVersion
|
||||
url = 'https://repo.viaversion.com/everything'
|
||||
}
|
||||
maven {
|
||||
// ViaBedrock snapshots (dependency of ViaFabricPlus)
|
||||
url = 'https://repo.opencollab.dev/maven-snapshots/'
|
||||
}
|
||||
maven {
|
||||
// ViaBedrock snapshots (alt repo used by Via* stack)
|
||||
url = 'https://maven.lenni0451.net/snapshots'
|
||||
}
|
||||
maven {
|
||||
// JitPack (for com.github.* artifacts like CubeConverter)
|
||||
url = 'https://jitpack.io'
|
||||
}
|
||||
maven {
|
||||
url = uri("$rootDir/local-maven")
|
||||
}
|
||||
}
|
||||
|
||||
version = project.mod_version
|
||||
group = project.maven_group
|
||||
|
||||
base {
|
||||
archivesName = project.archives_base_name
|
||||
}
|
||||
|
||||
def lovisualVulkanDebugEnabled = providers.gradleProperty("lovisualVulkanDebug")
|
||||
.map { it.toBoolean() }
|
||||
.orElse(false)
|
||||
def lovisualDevTaskRequested = gradle.startParameter.taskNames.any { it == "buildDev" || it.endsWith(":buildDev") }
|
||||
def lovisualDevEnabled = providers.gradleProperty("lovisualDev")
|
||||
.orElse(providers.gradleProperty("dev"))
|
||||
.orElse(providers.gradleProperty("devBuild"))
|
||||
.orElse(lovisualDevTaskRequested ? "true" : "false")
|
||||
.map { it.toBoolean() }
|
||||
.orElse(false)
|
||||
def svgMsdfGeneratedResources = layout.buildDirectory.dir("generated/resources/svgMsdf")
|
||||
def javetNativeGeneratedResources = layout.buildDirectory.dir("generated/resources/javetNatives")
|
||||
def javetVersion = "5.0.9"
|
||||
def targetJavaVersion = 25
|
||||
|
||||
sourceSets {
|
||||
main {
|
||||
resources.srcDir(svgMsdfGeneratedResources)
|
||||
}
|
||||
svgMsdfTool {
|
||||
java.srcDir("src/svgMsdfTool/java")
|
||||
compileClasspath += sourceSets.main.output.classesDirs + sourceSets.main.compileClasspath
|
||||
runtimeClasspath += output + compileClasspath
|
||||
}
|
||||
dev {
|
||||
java.srcDir("src/dev/java")
|
||||
resources.srcDir("src/dev/resources")
|
||||
compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath
|
||||
runtimeClasspath += output + compileClasspath
|
||||
}
|
||||
vulkanDebug {
|
||||
java.srcDir("src/vulkanDebug/java")
|
||||
resources.srcDir("src/vulkanDebug/resources")
|
||||
compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath
|
||||
runtimeClasspath += output + compileClasspath
|
||||
}
|
||||
}
|
||||
|
||||
configurations {
|
||||
bundledLibrary
|
||||
javetNativeBundle
|
||||
compileOnly.extendsFrom bundledLibrary
|
||||
runtimeOnly.extendsFrom bundledLibrary
|
||||
devImplementation.extendsFrom implementation
|
||||
devCompileOnly.extendsFrom compileOnly
|
||||
devAnnotationProcessor.extendsFrom annotationProcessor
|
||||
vulkanDebugImplementation.extendsFrom implementation
|
||||
vulkanDebugCompileOnly.extendsFrom compileOnly
|
||||
vulkanDebugAnnotationProcessor.extendsFrom annotationProcessor
|
||||
}
|
||||
|
||||
loom {
|
||||
mods {
|
||||
"lovisual" {
|
||||
sourceSet sourceSets.main
|
||||
if (lovisualDevEnabled.get()) {
|
||||
sourceSet sourceSets.dev
|
||||
}
|
||||
if (lovisualVulkanDebugEnabled.get()) {
|
||||
sourceSet sourceSets.vulkanDebug
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly 'org.projectlombok:lombok:1.18.46'
|
||||
annotationProcessor 'org.projectlombok:lombok:1.18.46'
|
||||
testCompileOnly 'org.projectlombok:lombok:1.18.46'
|
||||
testAnnotationProcessor 'org.projectlombok:lombok:1.18.46'
|
||||
testImplementation platform('org.junit:junit-bom:5.14.4')
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
devCompileOnly 'org.projectlombok:lombok:1.18.46'
|
||||
devAnnotationProcessor 'org.projectlombok:lombok:1.18.46'
|
||||
vulkanDebugCompileOnly 'org.projectlombok:lombok:1.18.46'
|
||||
vulkanDebugAnnotationProcessor 'org.projectlombok:lombok:1.18.46'
|
||||
|
||||
minecraft "com.mojang:minecraft:${project.minecraft_version}"
|
||||
implementation "net.fabricmc:fabric-loader:${project.loader_version}"
|
||||
implementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
|
||||
|
||||
|
||||
// Renderer targets. Sodium is required; Iris stays optional but available in dev runtime.
|
||||
compileOnly "maven.modrinth:sodium:${project.sodium_version}"
|
||||
compileOnly "maven.modrinth:iris:${project.iris_version}"
|
||||
compileOnly "maven.modrinth:immediatelyfast:${project.immediatelyfast_version}"
|
||||
if (providers.gradleProperty("withOptionalModRuntime").map { it.toBoolean() }.orElse(false).get()) {
|
||||
runtimeOnly "maven.modrinth:sodium:${project.sodium_version}"
|
||||
runtimeOnly "maven.modrinth:iris:${project.iris_version}"
|
||||
runtimeOnly "maven.modrinth:immediatelyfast:${project.immediatelyfast_version}"
|
||||
}
|
||||
|
||||
// Dev-only Xaero API for optional triangulator waypoint compat.
|
||||
// Pulled from Modrinth Maven so IDE sources/classes follow the selected MC version.
|
||||
compileOnly "maven.modrinth:xaeros-minimap:${project.xaero_minimap_version}"
|
||||
compileOnly "maven.modrinth:xaeros-world-map:${project.xaero_worldmap_version}"
|
||||
|
||||
// ViaFabricPlus (optional)
|
||||
compileOnly "com.viaversion:viafabricplus-api:${project.viafabricplus_version}"
|
||||
if (providers.gradleProperty("withViaFabricPlusRuntime").map { it.toBoolean() }.orElse(false).get()) {
|
||||
// Dev/runtime only (not bundled) to test locally.
|
||||
runtimeOnly "com.viaversion:viafabricplus:${project.viafabricplus_version}"
|
||||
}
|
||||
|
||||
// Entity Culling (optional): typed compile-time API for shader ESP visibility compat.
|
||||
compileOnly "maven.modrinth:entityculling:${project.entityculling_version}"
|
||||
|
||||
bundledLibrary "de.marhali:json5-java:3.0.0"
|
||||
|
||||
// Linux MPRIS backend for the built-in media session service.
|
||||
bundledLibrary "com.github.hypfvieh:dbus-java-core:4.3.1"
|
||||
bundledLibrary "com.github.hypfvieh:dbus-java-transport-native-unixsocket:4.3.1"
|
||||
|
||||
// Provided by Minecraft runtime; keep it out of the bundled jar.
|
||||
compileOnly 'com.google.code.gson:gson:2.14.0'
|
||||
|
||||
// Provided by Minecraft/Fabric runtime; do not shade it into the mod jar.
|
||||
compileOnly 'org.slf4j:slf4j-api:2.0.17'
|
||||
|
||||
bundledLibrary 'io.github.classgraph:classgraph:4.8.192'
|
||||
|
||||
// Javet core only. Native V8 binaries are copied into resources/javet/natives.
|
||||
bundledLibrary "com.caoccao.javet:javet:${javetVersion}"
|
||||
|
||||
// Javet in minimal V8 mode only: no Node runtime and no ARM native payloads.
|
||||
// ARM builds can be added later behind a separate opt-in distribution profile.
|
||||
javetNativeBundle "com.caoccao.javet:javet-v8-windows-x86_64:${javetVersion}"
|
||||
javetNativeBundle "com.caoccao.javet:javet-v8-linux-x86_64:${javetVersion}"
|
||||
javetNativeBundle "com.caoccao.javet:javet-v8-macos-x86_64:${javetVersion}"
|
||||
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
tasks.register("validateIrisPatches", JavaExec) {
|
||||
group = "verification"
|
||||
description = "Compiles bundled Iris patch manifests against a shaderpack zip without modifying it."
|
||||
dependsOn classes
|
||||
classpath = sourceSets.main.runtimeClasspath
|
||||
mainClass = "dev.loki.lovisual.render.iris.patch.ShaderPatchCompilerCli"
|
||||
doFirst {
|
||||
if (!project.hasProperty("shaderpack")) {
|
||||
throw new GradleException("Pass -Pshaderpack=<path-to-shaderpack.zip>")
|
||||
}
|
||||
args project.property("shaderpack")
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register("generateSvgMsdf", Exec) {
|
||||
group = "render assets"
|
||||
description = "Generates MTSDF texture assets for tintable SVG icons."
|
||||
dependsOn tasks.named("compileSvgMsdfToolJava")
|
||||
|
||||
def inputDir = file("src/main/resources/assets/lovisual/svg")
|
||||
def outputDir = svgMsdfGeneratedResources.map { it.dir("assets/lovisual/svg/msdf") }
|
||||
def script = file("tools/msdf/GenerateSvgMsdf.ps1")
|
||||
def preprocessorClasspath = sourceSets.svgMsdfTool.output.classesDirs.asPath +
|
||||
File.pathSeparator + sourceSets.main.output.classesDirs.asPath +
|
||||
File.pathSeparator + sourceSets.main.compileClasspath.asPath
|
||||
def generatorJava = javaToolchains.launcherFor {
|
||||
languageVersion = JavaLanguageVersion.of(targetJavaVersion)
|
||||
}
|
||||
inputs.files(fileTree(inputDir) {
|
||||
include "**/*.svg"
|
||||
exclude "msdf/**"
|
||||
})
|
||||
inputs.file(script)
|
||||
outputs.dir(outputDir)
|
||||
onlyIf {
|
||||
if (!script.isFile()) {
|
||||
logger.warn("SVG MSDF generator missing: ${script}")
|
||||
return false
|
||||
}
|
||||
if (!org.gradle.internal.os.OperatingSystem.current().isWindows()) {
|
||||
logger.warn("SVG MSDF generation requires Windows (PowerShell); skipping on ${org.gradle.internal.os.OperatingSystem.current().getFamilyName()}")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
doFirst {
|
||||
outputDir.get().asFile.mkdirs()
|
||||
}
|
||||
commandLine "powershell",
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy", "Bypass",
|
||||
"-File", script.absolutePath,
|
||||
"-InputRoot", inputDir.path,
|
||||
"-OutRoot", outputDir.get().asFile.path,
|
||||
"-PreprocessorClasspath", preprocessorClasspath,
|
||||
"-JavaExe", generatorJava.get().executablePath.asFile.absolutePath
|
||||
}
|
||||
|
||||
|
||||
tasks.register("unpackJavetNatives", Copy) {
|
||||
group = "runtime assets"
|
||||
description = "Copies bundled Javet V8 native binaries into generated resources."
|
||||
into javetNativeGeneratedResources.map { it.dir("javet/natives") }
|
||||
from({ configurations.javetNativeBundle.collect { zipTree(it) } }) {
|
||||
include "**/*.dll", "**/*.so", "**/*.dylib"
|
||||
eachFile { details ->
|
||||
details.path = details.name
|
||||
}
|
||||
includeEmptyDirs = false
|
||||
}
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
}
|
||||
|
||||
tasks.register("syncJavetNatives", Copy) {
|
||||
group = "runtime assets"
|
||||
description = "Copies Javet V8 native binaries into src/main/resources/javet/natives for committing/debugging."
|
||||
into file("src/main/resources/javet/natives")
|
||||
from({ configurations.javetNativeBundle.collect { zipTree(it) } }) {
|
||||
include "**/*.dll", "**/*.so", "**/*.dylib"
|
||||
eachFile { details ->
|
||||
details.path = details.name
|
||||
}
|
||||
includeEmptyDirs = false
|
||||
}
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
}
|
||||
|
||||
processResources {
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
dependsOn tasks.named("generateSvgMsdf")
|
||||
dependsOn tasks.named("unpackJavetNatives")
|
||||
from(javetNativeGeneratedResources)
|
||||
inputs.property "version", project.version
|
||||
inputs.property "minecraft_version", project.minecraft_version
|
||||
inputs.property "lovisual_dev", lovisualDevEnabled.get()
|
||||
inputs.property "lovisual_vulkan_debug", lovisualVulkanDebugEnabled.get()
|
||||
filteringCharset "UTF-8"
|
||||
|
||||
filesMatching("fabric.mod.json") {
|
||||
expand "version": project.version,
|
||||
"minecraft_version": project.minecraft_version,
|
||||
"loader_version": project.loader_version
|
||||
}
|
||||
|
||||
doLast {
|
||||
if (!lovisualDevEnabled.get() && !lovisualVulkanDebugEnabled.get()) return
|
||||
def metadataFile = new File(destinationDir, "fabric.mod.json")
|
||||
def metadata = new groovy.json.JsonSlurper().parse(metadataFile)
|
||||
def mixins = metadata.mixins instanceof java.util.Collection
|
||||
? new ArrayList(metadata.mixins)
|
||||
: new ArrayList()
|
||||
if (lovisualDevEnabled.get() && !mixins.contains("lovisual-dev.mixins.json")) {
|
||||
mixins.add("lovisual-dev.mixins.json")
|
||||
}
|
||||
if (!mixins.contains("lovisual-vulkan-debug.mixins.json")) {
|
||||
if (lovisualVulkanDebugEnabled.get()) {
|
||||
mixins.add("lovisual-vulkan-debug.mixins.json")
|
||||
}
|
||||
}
|
||||
metadata.mixins = mixins
|
||||
metadataFile.setText(
|
||||
groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(metadata)) + System.lineSeparator(),
|
||||
"UTF-8"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named("processDevResources") {
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
// ensure that the encoding is set to UTF-8, no matter what the system default is
|
||||
// this fixes some edge cases with special characters not displaying correctly
|
||||
// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html
|
||||
// If Javadoc is generated, this must be specified in that task too.
|
||||
it.options.encoding = "UTF-8"
|
||||
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
|
||||
it.options.release.set(targetJavaVersion)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named("compileDevJava").configure { enabled = lovisualDevEnabled.get() }
|
||||
tasks.named("processDevResources").configure { enabled = lovisualDevEnabled.get() }
|
||||
tasks.named("compileVulkanDebugJava").configure { enabled = lovisualVulkanDebugEnabled.get() }
|
||||
tasks.named("processVulkanDebugResources").configure { enabled = lovisualVulkanDebugEnabled.get() }
|
||||
|
||||
java {
|
||||
def javaVersion = JavaVersion.toVersion(targetJavaVersion)
|
||||
if (JavaVersion.current() < javaVersion) {
|
||||
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
|
||||
}
|
||||
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
|
||||
// if it is present.
|
||||
// If you remove this line, sources will not be generated.
|
||||
withSourcesJar()
|
||||
}
|
||||
|
||||
pmd {
|
||||
toolVersion = '7.27.0'
|
||||
ruleSetFiles = files("config/pmd/ruleset.xml")
|
||||
ruleSets = []
|
||||
ignoreFailures = true
|
||||
consoleOutput = true
|
||||
sourceSets = [sourceSets.main]
|
||||
}
|
||||
|
||||
checkstyle {
|
||||
toolVersion = '14.1.0'
|
||||
configFile = file("config/checkstyle/checkstyle.xml")
|
||||
ignoreFailures = true
|
||||
showViolations = true
|
||||
sourceSets = [sourceSets.main]
|
||||
}
|
||||
|
||||
spotbugs {
|
||||
toolVersion = '4.10.3'
|
||||
ignoreFailures = true
|
||||
showProgress = true
|
||||
}
|
||||
|
||||
spotbugsMain {
|
||||
reports {
|
||||
html.required = true
|
||||
xml.required = false
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType(com.github.spotbugs.snom.SpotBugsTask).configureEach {
|
||||
if (it.name != "spotbugsMain") {
|
||||
it.enabled = false
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register("checkFolderLimit") {
|
||||
group = "verification"
|
||||
description = "Проверяет правило ≤4 файла на папку (проектное)"
|
||||
doLast {
|
||||
def base = file("src/main/java")
|
||||
def bad = []
|
||||
base.eachDirRecurse { dir ->
|
||||
def files = dir.listFiles({ f -> f.name.endsWith(".java") } as FileFilter)
|
||||
def count = files != null ? files.length : 0
|
||||
if (count > 4) bad << "${dir} : ${count}"
|
||||
}
|
||||
if (!bad.isEmpty()) {
|
||||
logger.warn("Папок >4 файлов:\n" + bad.join("\n"))
|
||||
if (!project.hasProperty("ignoreFolderLimit")) {
|
||||
throw new GradleException("Правило ≤4 файла/папку нарушено:\n" + bad.join("\n") + "\nИсправь разбивкой на подпапки")
|
||||
}
|
||||
} else {
|
||||
logger.lifecycle("checkFolderLimit: OK (0 папок >4)")
|
||||
}
|
||||
}
|
||||
}
|
||||
check.dependsOn("checkFolderLimit")
|
||||
|
||||
tasks.matching { it.name == "sourcesJar" }.configureEach {
|
||||
dependsOn tasks.named("generateSvgMsdf")
|
||||
exclude("javet/natives/**")
|
||||
}
|
||||
|
||||
jar {
|
||||
manifest {
|
||||
attributes("Multi-Release": "true")
|
||||
}
|
||||
|
||||
from("LICENSE") {
|
||||
rename { "${it}_${project.archives_base_name}" }
|
||||
}
|
||||
from {
|
||||
configurations.bundledLibrary.collect { it.isDirectory() ? it : zipTree(it) }
|
||||
}
|
||||
exclude "com/google/gson/**"
|
||||
exclude "org/slf4j/**"
|
||||
exclude "META-INF/*.RSA", "META-INF/*.SF", "META-INF/*.DSA"
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
|
||||
if (lovisualDevEnabled.get()) {
|
||||
dependsOn tasks.named("compileDevJava"), tasks.named("processDevResources")
|
||||
from(sourceSets.dev.output)
|
||||
}
|
||||
if (lovisualVulkanDebugEnabled.get()) {
|
||||
dependsOn tasks.named("compileVulkanDebugJava"), tasks.named("processVulkanDebugResources")
|
||||
from(sourceSets.vulkanDebug.output)
|
||||
}
|
||||
}
|
||||
|
||||
// Gradle cannot accept an arbitrary global `--dev` flag for the built-in `build` task
|
||||
// from build.gradle itself. Use this alias or `-PlovisualDev=true`.
|
||||
tasks.register("buildDev") {
|
||||
group = "build"
|
||||
description = "Builds LoVisual with development source set and dev metadata enabled."
|
||||
dependsOn "build"
|
||||
}
|
||||
|
||||
// configure the maven publication
|
||||
publishing {
|
||||
publications {
|
||||
create("mavenJava", MavenPublication) {
|
||||
artifactId = project.archives_base_name
|
||||
from components.java
|
||||
}
|
||||
}
|
||||
|
||||
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
|
||||
repositories {
|
||||
maven {
|
||||
name = "GitHubPackages"
|
||||
url = uri("https://maven.pkg.github.com/loki5512344/lovisual-client")
|
||||
credentials {
|
||||
username = findProperty("gpr.user") ?: System.getenv("GITHUB_ACTOR") ?: ""
|
||||
password = findProperty("gpr.key") ?: System.getenv("GITHUB_TOKEN") ?: System.getenv("GH_TOKEN") ?: ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
51
mod/config/checkstyle/checkstyle.xml
Normal file
51
mod/config/checkstyle/checkstyle.xml
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
<?xml version="1.0"?>
|
||||
<!DOCTYPE module PUBLIC
|
||||
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
|
||||
"https://checkstyle.org/dtds/configuration_1_3.dtd">
|
||||
<module name="Checker">
|
||||
<property name="severity" value="warning"/>
|
||||
<property name="fileExtensions" value="java"/>
|
||||
|
||||
<module name="FileLength">
|
||||
<property name="max" value="200"/>
|
||||
<message key="maxLen.file" value="Файл {1} строк > 200 (правило проекта, фасад-исключение помечай @SuppressWarnings)"/>
|
||||
</module>
|
||||
|
||||
<module name="LineLength">
|
||||
<property name="max" value="140"/>
|
||||
<property name="ignorePattern" value="^(import|package).*"/>
|
||||
</module>
|
||||
|
||||
<module name="TreeWalker">
|
||||
<!-- Google base + проектные -->
|
||||
<module name="AvoidStarImport">
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
<module name="MagicNumber">
|
||||
<property name="ignoreNumbers" value="-1, 0, 1, 2"/>
|
||||
<property name="ignoreHashCodeMethod" value="true"/>
|
||||
<property name="ignoreAnnotation" value="true"/>
|
||||
</module>
|
||||
<module name="VisibilityModifier">
|
||||
<property name="packageAllowed" value="true"/>
|
||||
<property name="protectedAllowed" value="true"/>
|
||||
</module>
|
||||
<module name="MethodLength">
|
||||
<property name="max" value="40"/>
|
||||
</module>
|
||||
<module name="AvoidInlineConditionals"/>
|
||||
<module name="EmptyBlock">
|
||||
<property name="option" value="statement"/>
|
||||
</module>
|
||||
<module name="NeedBraces"/>
|
||||
<module name="LeftCurly"/>
|
||||
<module name="RightCurly"/>
|
||||
<module name="WhitespaceAround"/>
|
||||
<module name="NoWhitespaceBefore"/>
|
||||
<module name="GenericWhitespace"/>
|
||||
<module name="IllegalImport">
|
||||
<property name="illegalPkgs" value="java.awt, javax.swing"/>
|
||||
</module>
|
||||
<!-- ≤4 файла на папку Checkstyle не умеет — проверяется скриптом tools/check_folders.sh -->
|
||||
</module>
|
||||
</module>
|
||||
28
mod/config/lovisual/hud/draggable/admins.json
Normal file
28
mod/config/lovisual/hud/draggable/admins.json
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"layout": {
|
||||
"pos": [
|
||||
16.0,
|
||||
212.0
|
||||
],
|
||||
"space": "logical",
|
||||
"parent": "keybinds",
|
||||
"side": "RIGHT",
|
||||
"pox": 0.0,
|
||||
"poy": 0.0
|
||||
},
|
||||
"admins_scale": 1.0,
|
||||
"admins_layout": "Split Header",
|
||||
"admins_color_mode": "Theme",
|
||||
"admins_bg": "#EB111318",
|
||||
"admins_bg_secondary": "#F7161616",
|
||||
"admins_stroke": "#5A5A5A",
|
||||
"admins_bg_alpha": 131.0,
|
||||
"admins_text": "#FFFFFF",
|
||||
"admins_muted": "#A5A5A5",
|
||||
"admins_bg_effect": "Blur",
|
||||
"admins_blur_alpha": 255.0,
|
||||
"admins_header_icon_pulse": true,
|
||||
"admins_header_icon_pulse_speed": 18.0,
|
||||
"admins_header_icon_pulse_intensity": 100.0
|
||||
}
|
||||
17
mod/config/lovisual/hud/draggable/armor.json
Normal file
17
mod/config/lovisual/hud/draggable/armor.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"layout": {
|
||||
"pos": [
|
||||
1616.315,
|
||||
1003.6977
|
||||
],
|
||||
"space": "logical"
|
||||
},
|
||||
"armor_scale": 3.68,
|
||||
"armor_layout": "Horizontal",
|
||||
"armor_reverse": false,
|
||||
"armor_state_mode": "Text",
|
||||
"armor_state_bar_threshold": 70.0,
|
||||
"armor_state_threshold": 70.0,
|
||||
"armor_state_color_threshold": 70.0
|
||||
}
|
||||
27
mod/config/lovisual/hud/draggable/better_chat.json
Normal file
27
mod/config/lovisual/hud/draggable/better_chat.json
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"layout": {
|
||||
"pos": [
|
||||
16.0,
|
||||
485.12
|
||||
],
|
||||
"space": "logical"
|
||||
},
|
||||
"width_ratio": 0.54,
|
||||
"font_scale": 1.36,
|
||||
"lines": 12.0,
|
||||
"fade_seconds": 14.98,
|
||||
"liquid_glass_alpha": 230.0,
|
||||
"hide_vanilla": true,
|
||||
"history_enabled": true,
|
||||
"history_limit": 32000.0,
|
||||
"timestamps_enabled": true,
|
||||
"timestamp_color": "#C6D2CD",
|
||||
"timestamp_toggles": {
|
||||
"with_seconds": false,
|
||||
"with_brackets": true,
|
||||
"active_only": false,
|
||||
"hover_unix": false,
|
||||
"hover_date": true
|
||||
}
|
||||
}
|
||||
3
mod/config/lovisual/hud/draggable/combat_log.json
Normal file
3
mod/config/lovisual/hud/draggable/combat_log.json
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"enabled": false
|
||||
}
|
||||
18
mod/config/lovisual/hud/draggable/fps.json
Normal file
18
mod/config/lovisual/hud/draggable/fps.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"fps_scale": 2.37,
|
||||
"fps_color_mode": "Theme",
|
||||
"fps_icon_color": "#FFFFFF",
|
||||
"fps_value_color": "#FFFFFF",
|
||||
"fps_meta_color": "#9B9B9B",
|
||||
"fps_bg_effect": "Blur",
|
||||
"fps_bg": "#F7343434",
|
||||
"fps_bg_secondary": "#F7161616",
|
||||
"fps_stroke": "#5A5A5A",
|
||||
"fps_bg_alpha": 133.0,
|
||||
"fps_blur_alpha": 255.0,
|
||||
"fps_label_effect": "Flow",
|
||||
"fps_label_effect_speed": 18.0,
|
||||
"fps_digit_animation": false,
|
||||
"fps_digit_poll_ms": 495.0
|
||||
}
|
||||
16
mod/config/lovisual/hud/draggable/game_time.json
Normal file
16
mod/config/lovisual/hud/draggable/game_time.json
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"game_time_weather": true,
|
||||
"game_time_scale": 2.37,
|
||||
"game_time_color_mode": "Theme",
|
||||
"game_time_icon_color": "#FFFFFF",
|
||||
"game_time_value_color": "#FFFFFF",
|
||||
"game_time_bg_effect": "None",
|
||||
"game_time_bg": "#EB111318",
|
||||
"game_time_bg_secondary": "#F7161616",
|
||||
"game_time_stroke": "#5A5A5A",
|
||||
"game_time_bg_alpha": 235.0,
|
||||
"game_time_blur_alpha": 140.0,
|
||||
"game_time_icon_effect": "Mix",
|
||||
"game_time_icon_effect_speed": 18.0
|
||||
}
|
||||
9
mod/config/lovisual/hud/draggable/hud_notifier.json
Normal file
9
mod/config/lovisual/hud/draggable/hud_notifier.json
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"duration_ms": 2000.0,
|
||||
"fade_ms": 250.0,
|
||||
"scale": 1.35,
|
||||
"sound": true,
|
||||
"sound_mode": "2",
|
||||
"sound_volume": 0.47
|
||||
}
|
||||
25
mod/config/lovisual/hud/draggable/inventory.json
Normal file
25
mod/config/lovisual/hud/draggable/inventory.json
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"layout": {
|
||||
"pos": [
|
||||
1255.352,
|
||||
658.36005
|
||||
],
|
||||
"space": "logical"
|
||||
},
|
||||
"toggle_bind": "I",
|
||||
"inventory_scale": 1.32,
|
||||
"inventory_layout": "Unified Divider",
|
||||
"inventory_color_mode": "Theme",
|
||||
"inventory_bg": "#F7343434",
|
||||
"inventory_bg_secondary": "#F7161616",
|
||||
"inventory_stroke": "#5A5A5A",
|
||||
"inventory_bg_alpha": 194.0,
|
||||
"inventory_text": "#FFFFFF",
|
||||
"inventory_muted": "#A5A5A5",
|
||||
"inventory_bg_effect": "Blur",
|
||||
"inventory_blur_alpha": 255.0,
|
||||
"inventory_header_icon_pulse": true,
|
||||
"inventory_header_icon_pulse_speed": 15.0,
|
||||
"inventory_header_icon_pulse_intensity": 100.0
|
||||
}
|
||||
22
mod/config/lovisual/hud/draggable/itemizer.json
Normal file
22
mod/config/lovisual/hud/draggable/itemizer.json
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"layout": {
|
||||
"pos": [
|
||||
-16.0,
|
||||
48.0
|
||||
],
|
||||
"space": "logical",
|
||||
"ax": "CENTER",
|
||||
"ay": "CENTER"
|
||||
},
|
||||
"itemizer_scale": 1.0,
|
||||
"itemizer_display_mode": "icons",
|
||||
"itemizer_direction": "horizontal",
|
||||
"itemizer_duration": 1.15,
|
||||
"itemizer_max_entries": 3.0,
|
||||
"itemizer_auto_eat": true,
|
||||
"itemizer_auto_totem": true,
|
||||
"itemizer_elytra_swap": true,
|
||||
"itemizer_blur": true,
|
||||
"itemizer_bg_alpha": 168.0
|
||||
}
|
||||
33
mod/config/lovisual/hud/draggable/keybinds.json
Normal file
33
mod/config/lovisual/hud/draggable/keybinds.json
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"layout": {
|
||||
"pos": [
|
||||
456.6228,
|
||||
248.0
|
||||
],
|
||||
"space": "logical",
|
||||
"parent": "potions",
|
||||
"side": "RIGHT",
|
||||
"pox": 0.0,
|
||||
"poy": 0.0
|
||||
},
|
||||
"keybinds_scale": 1.0,
|
||||
"keybinds_layout": "Unified Divider",
|
||||
"keybinds_color_mode": "Theme",
|
||||
"keybinds_bg": "#F7343434",
|
||||
"keybinds_bg_secondary": "#F7161616",
|
||||
"keybinds_stroke": "#5A5A5A",
|
||||
"keybinds_bg_alpha": 225.0,
|
||||
"keybinds_text": "#FFFFFF",
|
||||
"keybinds_muted": "#A5A5A5",
|
||||
"keybinds_bg_effect": "None",
|
||||
"keybinds_blur_alpha": 140.0,
|
||||
"keybinds_local_actions": true,
|
||||
"keybinds_local_action_modes": {
|
||||
"Press": true,
|
||||
"Hold": true
|
||||
},
|
||||
"keybinds_header_icon_pulse": true,
|
||||
"keybinds_header_icon_pulse_speed": 18.0,
|
||||
"keybinds_header_icon_pulse_intensity": 100.0
|
||||
}
|
||||
19
mod/config/lovisual/hud/draggable/media_player.json
Normal file
19
mod/config/lovisual/hud/draggable/media_player.json
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"layout": {
|
||||
"pos": [
|
||||
12.0,
|
||||
82.30222
|
||||
],
|
||||
"space": "logical"
|
||||
},
|
||||
"media_player_scale": 1.51,
|
||||
"media_player_sync_theme": true,
|
||||
"media_player_bg": "#60000000",
|
||||
"media_player_bg_alpha": 124.0,
|
||||
"media_player_accent": "#FF2F2F",
|
||||
"media_player_text": "#FFFFFF",
|
||||
"media_player_bg_effect": "None",
|
||||
"media_player_blur_alpha": 255.0,
|
||||
"media_player_gradient": true
|
||||
}
|
||||
17
mod/config/lovisual/hud/draggable/memory.json
Normal file
17
mod/config/lovisual/hud/draggable/memory.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"memory_scale": 2.37,
|
||||
"memory_color_mode": "Theme",
|
||||
"memory_icon_color": "#FFFFFF",
|
||||
"memory_value_color": "#FFFFFF",
|
||||
"memory_meta_color": "#9B9B9B",
|
||||
"memory_extra_color": "#BEBEBE",
|
||||
"memory_bg_effect": "Blur",
|
||||
"memory_bg": "#F7343434",
|
||||
"memory_bg_secondary": "#F7161616",
|
||||
"memory_stroke": "#5A5A5A",
|
||||
"memory_bg_alpha": 135.0,
|
||||
"memory_blur_alpha": 255.0,
|
||||
"memory_label_effect": "None",
|
||||
"memory_label_effect_speed": 18.0
|
||||
}
|
||||
16
mod/config/lovisual/hud/draggable/module_list.json
Normal file
16
mod/config/lovisual/hud/draggable/module_list.json
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"module_list_scale": 3.67,
|
||||
"module_list_color_mode": "Custom",
|
||||
"module_list_bg_effect": "Blur",
|
||||
"module_list_bg_alpha": 226.0,
|
||||
"module_list_blur_alpha": 255.0,
|
||||
"module_list_bg": "#FF444242",
|
||||
"module_list_bg_secondary": "#22000000",
|
||||
"module_list_text": "RNB#E87171",
|
||||
"module_list_text_secondary": "#93118C",
|
||||
"module_list_text_gradient_mode": "rainbow",
|
||||
"module_list_text_gradient_speed": 18.0,
|
||||
"module_list_text_effect": "None",
|
||||
"module_list_text_effect_speed": 30.0
|
||||
}
|
||||
16
mod/config/lovisual/hud/draggable/ping.json
Normal file
16
mod/config/lovisual/hud/draggable/ping.json
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"ping_scale": 2.58,
|
||||
"ping_color_mode": "Theme",
|
||||
"ping_icon_color": "#FFFFFF",
|
||||
"ping_value_color": "#FFFFFF",
|
||||
"ping_meta_color": "#9B9B9B",
|
||||
"ping_bg_effect": "None",
|
||||
"ping_bg": "#F7343434",
|
||||
"ping_bg_secondary": "#F7161616",
|
||||
"ping_stroke": "#5A5A5A",
|
||||
"ping_bg_alpha": 225.0,
|
||||
"ping_blur_alpha": 140.0,
|
||||
"ping_label_effect": "None",
|
||||
"ping_label_effect_speed": 18.0
|
||||
}
|
||||
24
mod/config/lovisual/hud/draggable/potions.json
Normal file
24
mod/config/lovisual/hud/draggable/potions.json
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"layout": {
|
||||
"pos": [
|
||||
31.729004,
|
||||
182.0
|
||||
],
|
||||
"space": "logical"
|
||||
},
|
||||
"potions_scale": 1.05,
|
||||
"potions_layout": "Unified Divider",
|
||||
"potions_color_mode": "Theme",
|
||||
"potions_bg": "#EB784F4F",
|
||||
"potions_bg_secondary": "#F7161616",
|
||||
"potions_stroke": "#5A5A5A",
|
||||
"potions_bg_alpha": 200.0,
|
||||
"potions_text": "#FFFFFF",
|
||||
"potions_muted": "#A5A5A5",
|
||||
"potions_bg_effect": "Blur",
|
||||
"potions_blur_alpha": 159.0,
|
||||
"potions_header_icon_pulse": true,
|
||||
"potions_header_icon_pulse_speed": 18.0,
|
||||
"potions_header_icon_pulse_intensity": 100.0
|
||||
}
|
||||
24
mod/config/lovisual/hud/draggable/radar.json
Normal file
24
mod/config/lovisual/hud/draggable/radar.json
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"layout": {
|
||||
"pos": [
|
||||
1666.0,
|
||||
17.915222
|
||||
],
|
||||
"space": "logical"
|
||||
},
|
||||
"radar_mode": "Rect",
|
||||
"radar_color_mode": "Sync",
|
||||
"radar_size": 217.27,
|
||||
"radar_bg_color": "#CC101010",
|
||||
"radar_bg_alpha": 109.0,
|
||||
"radar_text_color": "#FFFFFF",
|
||||
"radar_field_1": "Name",
|
||||
"radar_field_2": "Hp",
|
||||
"radar_field_3": "Ping",
|
||||
"radar_field_4": "None",
|
||||
"radar_field_5": "None",
|
||||
"radar_blur": true,
|
||||
"radar_blur_alpha": 255.0,
|
||||
"radar_gradient": false
|
||||
}
|
||||
31
mod/config/lovisual/hud/draggable/scoreboard.json
Normal file
31
mod/config/lovisual/hud/draggable/scoreboard.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"layout": {
|
||||
"pos": [
|
||||
1721.69,
|
||||
158.0
|
||||
],
|
||||
"space": "logical"
|
||||
},
|
||||
"toggle_bind": "Э",
|
||||
"scoreboard_scale": 1.93,
|
||||
"scoreboard_color_mode": "Theme",
|
||||
"scoreboard_bg_effect": "Blur",
|
||||
"scoreboard_bg_alpha": 182.0,
|
||||
"scoreboard_blur_alpha": 255.0,
|
||||
"scoreboard_bg": "#820A0A0A",
|
||||
"scoreboard_bg_secondary": "#B8141414",
|
||||
"scoreboard_stroke": "#4A4A4A",
|
||||
"scoreboard_title_color": "#FFCC00",
|
||||
"scoreboard_label_color": "#FFFFFF",
|
||||
"scoreboard_value_color": "#FF4A4A",
|
||||
"scoreboard_footer_color": "#FFD44A",
|
||||
"scoreboard_text_effect": "Stripe",
|
||||
"scoreboard_text_effect_speed": 18.0,
|
||||
"scoreboard_text_effect_sections": {
|
||||
"header": true,
|
||||
"labels": false,
|
||||
"values": false,
|
||||
"footer": false
|
||||
}
|
||||
}
|
||||
18
mod/config/lovisual/hud/draggable/speed_bps.json
Normal file
18
mod/config/lovisual/hud/draggable/speed_bps.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"speed_bps_bps": true,
|
||||
"speed_bps_average": false,
|
||||
"speed_bps_scale": 2.37,
|
||||
"speed_bps_color_mode": "Theme",
|
||||
"speed_bps_icon_color": "#FFFFFF",
|
||||
"speed_bps_value_color": "#FFFFFF",
|
||||
"speed_bps_meta_color": "#9B9B9B",
|
||||
"speed_bps_bg_effect": "Blur",
|
||||
"speed_bps_bg": "#F7343434",
|
||||
"speed_bps_bg_secondary": "#F7161616",
|
||||
"speed_bps_stroke": "#5A5A5A",
|
||||
"speed_bps_bg_alpha": 135.0,
|
||||
"speed_bps_blur_alpha": 255.0,
|
||||
"speed_bps_label_effect": "Mix",
|
||||
"speed_bps_label_effect_speed": 60.0
|
||||
}
|
||||
16
mod/config/lovisual/hud/draggable/system_time.json
Normal file
16
mod/config/lovisual/hud/draggable/system_time.json
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"system_time_seconds": false,
|
||||
"system_time_scale": 2.37,
|
||||
"system_time_color_mode": "Theme",
|
||||
"system_time_icon_color": "#FFFFFF",
|
||||
"system_time_value_color": "#FFFFFF",
|
||||
"system_time_bg_effect": "Blur",
|
||||
"system_time_bg": "#EB111318",
|
||||
"system_time_bg_secondary": "#F7161616",
|
||||
"system_time_stroke": "#5A5A5A",
|
||||
"system_time_bg_alpha": 235.0,
|
||||
"system_time_blur_alpha": 140.0,
|
||||
"system_time_icon_effect": "None",
|
||||
"system_time_icon_effect_speed": 18.0
|
||||
}
|
||||
41
mod/config/lovisual/hud/draggable/target_hud.json
Normal file
41
mod/config/lovisual/hud/draggable/target_hud.json
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"layout": {
|
||||
"pos": [
|
||||
7.6799927,
|
||||
721.12
|
||||
],
|
||||
"space": "logical",
|
||||
"ax": "CENTER"
|
||||
},
|
||||
"target_scale": 3.28,
|
||||
"target_hold_ms": 1000.0,
|
||||
"totem_pop_counter": true,
|
||||
"totem_pop_reset_seconds": 300.0,
|
||||
"target_totem_pop_text_color": "RNB#FFFFFF",
|
||||
"target_marquee": true,
|
||||
"target_players_only": false,
|
||||
"target_effects_mode": "Off",
|
||||
"target_effects_self": true,
|
||||
"target_equipment_mode": "Off",
|
||||
"target_hp_mode": "Arc",
|
||||
"target_color_mode": "Theme",
|
||||
"target_bg": "#F7343434",
|
||||
"target_bg_secondary": "#F7161616",
|
||||
"target_stroke": "#5A5A5A",
|
||||
"target_bg_alpha": 162.0,
|
||||
"target_text": "#FFFFFF",
|
||||
"target_text_secondary": "#D7D7D7",
|
||||
"target_bar_bg": "#1E1E1E",
|
||||
"target_health_start": "#F3F3F3",
|
||||
"target_health_end": "#9E9E9E",
|
||||
"target_trail": "#373737",
|
||||
"target_absorption_start": "#FFC300",
|
||||
"target_absorption_end": "#FFD96B",
|
||||
"target_hit_outer": "#FF5A5A",
|
||||
"target_hit_inner": "#FF7373",
|
||||
"target_bg_effect": "Glass",
|
||||
"target_blur_alpha": 255.0,
|
||||
"target_hit_anim": true,
|
||||
"target_hit_pulse": 1.0
|
||||
}
|
||||
21
mod/config/lovisual/hud/draggable/timer_indicator.json
Normal file
21
mod/config/lovisual/hud/draggable/timer_indicator.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"layout": {
|
||||
"pos": [
|
||||
1242.2065,
|
||||
889.5111
|
||||
],
|
||||
"space": "logical"
|
||||
},
|
||||
"scale": 1.0,
|
||||
"always_show": true,
|
||||
"sync_theme": true,
|
||||
"blur": false,
|
||||
"blur_alpha": 140.0,
|
||||
"blur_bg_alpha": 128.0,
|
||||
"gradient": true,
|
||||
"bg": "#B012151B",
|
||||
"bar_start": "#5CC8E7",
|
||||
"bar_end": "#55FFFF",
|
||||
"text_color": "#FFFFFF"
|
||||
}
|
||||
18
mod/config/lovisual/hud/draggable/tps.json
Normal file
18
mod/config/lovisual/hud/draggable/tps.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"tps_extra": false,
|
||||
"tps_scale": 2.37,
|
||||
"tps_color_mode": "Theme",
|
||||
"tps_icon_color": "#FFFFFF",
|
||||
"tps_value_color": "#FFFFFF",
|
||||
"tps_meta_color": "#9B9B9B",
|
||||
"tps_extra_color": "#BEBEBE",
|
||||
"tps_bg_effect": "Blur",
|
||||
"tps_bg": "#F7343434",
|
||||
"tps_bg_secondary": "#F7161616",
|
||||
"tps_stroke": "#5A5A5A",
|
||||
"tps_bg_alpha": 133.0,
|
||||
"tps_blur_alpha": 255.0,
|
||||
"tps_label_effect": "None",
|
||||
"tps_label_effect_speed": 18.0
|
||||
}
|
||||
29
mod/config/lovisual/hud/draggable/triangulator.json
Normal file
29
mod/config/lovisual/hud/draggable/triangulator.json
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
{
|
||||
"enabled": false,
|
||||
"layout": {
|
||||
"pos": [
|
||||
1302.04,
|
||||
330.69208
|
||||
],
|
||||
"space": "logical"
|
||||
},
|
||||
"triangulator_scale": 1.68,
|
||||
"triangulator_color_mode": "Theme",
|
||||
"triangulator_bg": "#F7343434",
|
||||
"triangulator_bg_secondary": "#F7161616",
|
||||
"triangulator_stroke": "#5A5A5A",
|
||||
"triangulator_bg_alpha": 225.0,
|
||||
"triangulator_text": "#FFFFFF",
|
||||
"triangulator_muted": "#A5A5A5",
|
||||
"triangulator_bg_effect": "Blur",
|
||||
"triangulator_blur_alpha": 140.0,
|
||||
"triangulator_icon_effect": "None",
|
||||
"triangulator_icon_effect_speed": 18.0,
|
||||
"triangulator_min_observation_ticks": 6.0,
|
||||
"triangulator_stability_threshold": 0.99,
|
||||
"triangulator_min_pair_angle": 6.0,
|
||||
"triangulator_auto_reset": true,
|
||||
"triangulator_auto_reset_distance": 96.0,
|
||||
"triangulator_max_cached_throws": 6.0,
|
||||
"triangulator_cache_lifetime": 180.0
|
||||
}
|
||||
13
mod/config/lovisual/hud/draggable/watermark.json
Normal file
13
mod/config/lovisual/hud/draggable/watermark.json
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"watermark_scale": 1.0,
|
||||
"watermark_color_mode": "Theme",
|
||||
"watermark_show_fps": true,
|
||||
"watermark_show_ping": true,
|
||||
"watermark_show_server": true,
|
||||
"watermark_show_user": false,
|
||||
"watermark_show_dimensions": false,
|
||||
"watermark_title_color": "#5CC8E7",
|
||||
"watermark_meta_color": "#9B9B9B",
|
||||
"watermark_bg_color": "#1A1D23"
|
||||
}
|
||||
18
mod/config/lovisual/hud/draggable/xyz.json
Normal file
18
mod/config/lovisual/hud/draggable/xyz.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"xyz_nether": "On",
|
||||
"xyz_scale": 2.37,
|
||||
"xyz_color_mode": "Theme",
|
||||
"xyz_icon_color": "#FFFFFF",
|
||||
"xyz_label_color": "#9B9B9B",
|
||||
"xyz_value_color": "#FFFFFF",
|
||||
"xyz_extra_color": "#BEBEBE",
|
||||
"xyz_bg_effect": "Blur",
|
||||
"xyz_bg": "#F7343434",
|
||||
"xyz_bg_secondary": "#F7161616",
|
||||
"xyz_stroke": "#5A5A5A",
|
||||
"xyz_bg_alpha": 184.0,
|
||||
"xyz_blur_alpha": 255.0,
|
||||
"xyz_label_effect": "Flow",
|
||||
"xyz_label_effect_speed": 18.0
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"dynamic_island_sync_theme": true,
|
||||
"dynamic_island_theme_alpha": 200.0,
|
||||
"dynamic_island_blur": false,
|
||||
"dynamic_island_blur_alpha": 120.0,
|
||||
"dynamic_island_bg": "#E614171D",
|
||||
"dynamic_island_accent": "#6E8DFF",
|
||||
"dynamic_island_text": "#F5F7FA",
|
||||
"dynamic_island_muted": "#A9B1BC"
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"reach_scale": 1.0,
|
||||
"reach_keep_ms": 2500.0,
|
||||
"reach_sync_theme": true,
|
||||
"reach_show_max": true,
|
||||
"reach_highlight_overreach": true,
|
||||
"reach_value_color": "#5CC8E7",
|
||||
"reach_bg_color": "#1A1D23"
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"swap_scale": 0.24,
|
||||
"swap_offset_y": 66.6,
|
||||
"swap_text_effect": "Mix",
|
||||
"swap_text_effect_speed": 18.0
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"tab_list_max_width": 1680.0,
|
||||
"tab_list_sync_theme": true,
|
||||
"tab_list_theme_alpha": 225.0,
|
||||
"tab_list_bg": "#E50B1018",
|
||||
"tab_list_accent": "#6E8DFF",
|
||||
"tab_list_text": "#F4F7FB",
|
||||
"tab_list_muted": "#9AA5B5"
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"xp_bar": true,
|
||||
"xp_bar_show_level": true,
|
||||
"bar_mode": "level",
|
||||
"bar_color_mode": "Theme",
|
||||
"custom_bg_color": "#88151515",
|
||||
"custom_fill_color": "#CC4CB2FF",
|
||||
"custom_fill_gradient_color": "#CC76F0FF",
|
||||
"custom_text_color": "#FFA0E5FF",
|
||||
"locator_labels": true,
|
||||
"locator_label_mode": "center",
|
||||
"locator_label_angle": 6.0,
|
||||
"locator_label_distance": true,
|
||||
"locator_search_enabled": true,
|
||||
"locator_search_list": [
|
||||
"imhorny"
|
||||
],
|
||||
"locator_dimmed_color": "#777777",
|
||||
"locator_search_color": "#FFAA00",
|
||||
"locator_dimmed_scale_only": true,
|
||||
"locator_map_filter_enabled": false,
|
||||
"locator_map_server": "",
|
||||
"locator_map_url": "example",
|
||||
"locator_target_toggle": "NONE",
|
||||
"locator_bar_toggle": "U"
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"style": "Default",
|
||||
"gradient_base_color": "#FF2F2929",
|
||||
"gradient_color": "#FF902F2F",
|
||||
"gradient_angle": 74.25,
|
||||
"gradient_intensity": 0.6,
|
||||
"custom_bg": "#FF1B1B1B",
|
||||
"custom_bg_hover": "#FF2A2A2A",
|
||||
"custom_bg_disabled": "#FF141414",
|
||||
"custom_stroke": "#FF9B5DB8",
|
||||
"custom_stroke_hover": "#FFA710B2",
|
||||
"custom_stroke_disabled": "#FF2A2A2A",
|
||||
"custom_text": "#FFECECEC",
|
||||
"custom_text_disabled": "#FF7A7A7A",
|
||||
"custom_radius": 6.0,
|
||||
"custom_softness": 1.2,
|
||||
"custom_stroke_thickness": 0.7,
|
||||
"custom_gradient": true,
|
||||
"custom_gradient_color": "#73521BA7",
|
||||
"custom_gradient_angle": 90.0,
|
||||
"custom_gradient_intensity": 0.5,
|
||||
"custom_text_scale": 1.0,
|
||||
"custom_text_pad_x": 6.0
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"health_alpha": 255.0,
|
||||
"health_bar_style": "TargetHud",
|
||||
"custom_bar_radius": 5.0,
|
||||
"custom_text_scale": 0.24,
|
||||
"custom_text_padding": 3.0
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"offhand_mode": "merged",
|
||||
"hotbar_color_mode": "Custom",
|
||||
"bg_color": "#7A191414",
|
||||
"hotbar_bg_alpha": 167.0,
|
||||
"custom_select_color": false,
|
||||
"select_color": "#2F6277",
|
||||
"custom_divider_color": false,
|
||||
"divider_color": "#C13434",
|
||||
"accent_alpha": 255.0,
|
||||
"bg_effect": "Glass",
|
||||
"blur_alpha": 255.0
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"item_tooltip": true,
|
||||
"shulker_preview": true,
|
||||
"item_info_colorize": true,
|
||||
"tooltip_font": "Iosevka",
|
||||
"tooltip_text_size": 1.0,
|
||||
"top_enchant_ignore": [
|
||||
"minecraft:binding_curse",
|
||||
"minecraft:vanishing_curse",
|
||||
"minecraft:mending",
|
||||
"minecraft:infinity",
|
||||
"minecraft:silk_touch",
|
||||
"minecraft:aqua_affinity",
|
||||
"minecraft:flame",
|
||||
"minecraft:channeling",
|
||||
"minecraft:multishot",
|
||||
"minecraft:unbreaking"
|
||||
],
|
||||
"shulker_slot_size": 18.0,
|
||||
"shulker_preview_hold": "LEFT_SHIFT"
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"enabled": true,
|
||||
"watermark_scale": 1.0,
|
||||
"watermark_sync_theme": true,
|
||||
"watermark_show_version": true,
|
||||
"watermark_show_user": false,
|
||||
"watermark_show_fps": true,
|
||||
"watermark_show_ping": true,
|
||||
"watermark_title_color": "#5CC8E7",
|
||||
"watermark_meta_color": "#9B9B9B",
|
||||
"watermark_bg_color": "#1A1D23"
|
||||
}
|
||||
30
mod/config/lovisual/mainconfig.json5
Normal file
30
mod/config/lovisual/mainconfig.json5
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
'debug': 'off',
|
||||
'forcePvp': false,
|
||||
'menuBg': 'off',
|
||||
'menuClockShowSeconds': false,
|
||||
'menuBgUseTheme': false,
|
||||
'msaa3d': 'off',
|
||||
'clickGuiModulesHints': true,
|
||||
'clickGuiHudEditorHints': true,
|
||||
'inventorySwapPolicy': 'none',
|
||||
'inventorySwapScope': 'full',
|
||||
'inventorySwapVisibility': 'silent',
|
||||
'inventorySwapRestore': true,
|
||||
'inventorySwapPreferHotbar': true,
|
||||
'inventorySwapLegitWaitTicks': 2.0,
|
||||
'inventorySwapStrictInventoryWaitTicks': 1.0,
|
||||
'inventorySwapStrictMovementLockTicks': 2.0,
|
||||
'disableNarrator': true,
|
||||
'backdoorProtection': true,
|
||||
'backdoorTranslationFilter': true,
|
||||
'backdoorKeybindFilter': true,
|
||||
'backdoorLocalHttpGuard': true,
|
||||
'backdoorPackCacheIsolation': true,
|
||||
'backdoorAllowLocalHttpWhenServerLocal': true,
|
||||
'backdoorAllowedTranslationPacks': [
|
||||
'vanilla',
|
||||
],
|
||||
'backdoorAllowedKeybinds': [
|
||||
],
|
||||
}
|
||||
63
mod/config/pmd/ruleset.xml
Normal file
63
mod/config/pmd/ruleset.xml
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
<?xml version="1.0"?>
|
||||
<ruleset name="LoVisual"
|
||||
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
|
||||
|
||||
<description>LoVisual — bestpractices/errorprone/performance/security + проектные правила 200/4</description>
|
||||
|
||||
<!-- Базовые категории PMD 7.27.0 -->
|
||||
<rule ref="category/java/bestpractices.xml"/>
|
||||
<rule ref="category/java/errorprone.xml"/>
|
||||
<rule ref="category/java/performance.xml"/>
|
||||
<rule ref="category/java/security.xml"/>
|
||||
|
||||
<!-- Файл ≤200 строк: через ExcessiveClassLength (класс ≈ файл) -->
|
||||
<rule ref="category/java/design.xml/ExcessiveClassLength">
|
||||
<properties>
|
||||
<property name="minimum" value="200"/>
|
||||
</properties>
|
||||
</rule>
|
||||
|
||||
<!-- Кастом: System.currentTimeMillis → GameClock.millis() -->
|
||||
<rule name="SystemCurrentTimeMillisUsage"
|
||||
language="java"
|
||||
message="Используй GameClock.millis() вместо System.currentTimeMillis() в модулях"
|
||||
class="net.sourceforge.pmd.lang.rule.XPathRule">
|
||||
<description>Модули должны использовать игровое время GameClock.millis(), не стенное.</description>
|
||||
<priority>2</priority>
|
||||
<properties>
|
||||
<property name="xpath">
|
||||
<value><![CDATA[
|
||||
//PrimaryExpression[PrimaryPrefix/Name[@Image='System.currentTimeMillis']]
|
||||
]]></value>
|
||||
</property>
|
||||
</properties>
|
||||
</rule>
|
||||
|
||||
<!-- Кастом: static Minecraft в полях -->
|
||||
<rule name="StaticMinecraftField"
|
||||
language="java"
|
||||
message="Не храни static Minecraft в поле — только локально Minecraft.getInstance()"
|
||||
class="net.sourceforge.pmd.lang.rule.XPathRule">
|
||||
<description>Никакого static final Minecraft в полях (правило проекта).</description>
|
||||
<priority>2</priority>
|
||||
<properties>
|
||||
<property name="xpath">
|
||||
<value><![CDATA[
|
||||
//FieldDeclaration[@Static='true'][.//Type//Name[@Image='Minecraft']]
|
||||
]]></value>
|
||||
</property>
|
||||
</properties>
|
||||
</rule>
|
||||
|
||||
<!-- Пустые блоки / пустышки -->
|
||||
<rule ref="category/java/codestyle.xml/EmptyCatchBlock"/>
|
||||
<rule ref="category/java/codestyle.xml/EmptyIfStmt"/>
|
||||
<rule ref="category/java/bestpractices.xml/UnusedPrivateMethod"/>
|
||||
<rule ref="category/java/bestpractices.xml/UnusedPrivateField"/>
|
||||
|
||||
<!-- Исключения: сгенерированные, миксины, Faust -->
|
||||
<exclude-pattern>.*/build/.*</exclude-pattern>
|
||||
<exclude-pattern>.*/src/main/resources/.*</exclude-pattern>
|
||||
</ruleset>
|
||||
5
mod/docs/README.md
Normal file
5
mod/docs/README.md
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
# docs
|
||||
|
||||
- `DEV_GUIDE.md` — единый справочник разработчика (сборка, правила ≤200/≤4, пакеты, модули/HUD/команды/миксины/рендер/тесты). Объединён из `DEV_GUIDE.md`+`DEVELOPMENT.md` 2026-09-23.
|
||||
- `api/addons.md` — API аддонов (`lovisual:addon`, жизненный цикл, что может аддон). Публичный API можно ломать свободно при рефакторинге (KISS > совместимость).
|
||||
- `TODO.md` в корне — план фаз (сейчас 8.5/9.1/9.2/10/11).
|
||||
73
mod/docs/api/addons.md
Normal file
73
mod/docs/api/addons.md
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
# LoVisual Addon API (`api/v0`)
|
||||
|
||||
Аддоны — обычные Fabric-моды, которые расширяют LoVisual. Точка входа `lovisual:addon` в `fabric.mod.json`. Можно свободно менять публичный API при рефакторинге — владелец разрешил ломать совместимость ради KISS.
|
||||
|
||||
## Entrypoint
|
||||
|
||||
`fabric.mod.json`:
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "my-addon",
|
||||
"name": "My Addon",
|
||||
"entrypoints": {
|
||||
"lovisual:addon": ["com.example.MyAddon"]
|
||||
},
|
||||
"custom": {
|
||||
"lovisual:addon": { "api": 0, "icon": "assets/my-addon/icon.png" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Класс:
|
||||
```java
|
||||
public class MyAddon implements LoVisualAddon {
|
||||
public void onConfigureModules(LoVisualModuleLoadContext ctx) {
|
||||
ctx.disableBuiltInModule("killAura"); // выключить встроенный модуль до его создания
|
||||
}
|
||||
public void onInitialize(LoVisualAddonContext ctx) {
|
||||
ctx.registerModule(MyModule.class);
|
||||
ctx.registerDraggableHudElement(MyHud.class);
|
||||
ctx.registerStaticHudElement(MyStaticHud.class);
|
||||
ctx.registerCommand(new MyCommand());
|
||||
ctx.registerClickGuiSection(new MySection());
|
||||
ctx.addRenderCallback(LoVisualRenderStage.HUD_RAW, (c) -> { /* 2D */ });
|
||||
}
|
||||
public void onClientReady(LoVisualAddonRuntimeContext ctx) {}
|
||||
public void onShutdown(LoVisualAddonRuntimeContext ctx) {}
|
||||
public void onRuntimeSuspended(LoVisualAddonRuntimeContext ctx) {} // при выкл. аддона
|
||||
public void onRuntimeResumed(LoVisualAddonRuntimeContext ctx) {}
|
||||
}
|
||||
```
|
||||
|
||||
`LoVisualAddon.API_VERSION = 0` — сверяется в `AddonManager.java:438`, несовпадение → `WARNING`.
|
||||
|
||||
## Жизнь аддона (`AddonManager.java:39`)
|
||||
|
||||
1. `discoverEntrypoints:211` — `FabricLoader.getEntrypointContainers` → `ADDONS` map, `ENABLED_OVERRIDES` из `AddonStateStore` (вкл/выкл сохраняется).
|
||||
2. `prepareModuleLoading:58` — `configureEnabledAddons:230` → `onConfigureModules` (до `ModuleAutoLoader`).
|
||||
3. `init:65` — `reconcileModuleExclusions:255` + `initializeEnabledAddons:272` → `onInitialize`.
|
||||
4. `notifyClientReady:79` — `onClientReady` после загрузки конфигов.
|
||||
5. Вкл/выкл из `LoVisualAddonManagerScreen.java:548` `AddonManager.setEnabled:160` — `suspend/resumeRuntimeContributions:363` глушит модули/HUD, пишет `AddonStateStore`.
|
||||
|
||||
Статусы `AddonStatus.java:12`: `DISCOVERED → ACTIVE / DISABLED / ERROR / SUSPENDED`.
|
||||
|
||||
## Что может аддон
|
||||
|
||||
- **Модули** `ctx.registerModule(Class<? extends Module>)` — обычный `@ModuleInfo`, попадёт в `ModuleManager`, конфиг `addon:ID:module:ID`.
|
||||
- **HUD** `registerDraggableHudElement` / `registerStaticHudElement` — `@HudElementInfo` / `@HudElementRegister`, конфиг `addon:ID:hud.*`.
|
||||
- **Команды** `registerCommand(ClientCommand)` — `@CommandInfo`, префикс `%`.
|
||||
- **ClickGui секции** `registerClickGuiSection(LoVisualClickGuiSection)`.
|
||||
- **Рендер** `addRenderCallback(stage, callback)` / `addPostProcessCallback` — `LoVisualRenderStage` (`HUD_RAW`, `WORLD_*`).
|
||||
- **Расширения модулей** `LoVisualModuleExtension` — `beforeEnable/afterTick` и т.д. через `ModuleExtensionManager`.
|
||||
|
||||
Профили: `AddonManager.moduleProfileOwnerId:129` → `addon:ID:module:ID` для `.lvcfg`.
|
||||
|
||||
## Пример минимального аддона
|
||||
|
||||
См. `api/v0` JavaDoc и `addon/core/AddonManager.java:211`, `addon/pipeline/AddonSnapshot.java:14`, `features/gui/mainmenu/LoVisualAddonManagerScreen.java:48` (UI).
|
||||
|
||||
## Примечание по рефакторингу
|
||||
|
||||
Публичный Java API аддонов **можно ломать свободно** — KISS важнее обратной совместимости (решение владельца 2026-09-05, `TODO.md:9`). При рефакторе меняй сигнатуры, удаляй делегирование, обновляй вызывающих.
|
||||
|
||||
20
mod/gradle.properties
Normal file
20
mod/gradle.properties
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
# Done to increase the memory available to gradle.
|
||||
org.gradle.jvmargs=-Xmx2G
|
||||
# Fabric Properties
|
||||
# check these on https://modmuss50.me/fabric.html
|
||||
minecraft_version=26.2
|
||||
loader_version=0.19.4
|
||||
# Mod Properties
|
||||
mod_version=0.1.1
|
||||
maven_group=dev.loki
|
||||
archives_base_name=lovisual
|
||||
# Dependencies
|
||||
# check this on https://modmuss50.me/fabric.html
|
||||
fabric_version=0.152.2+26.2
|
||||
sodium_version=mc26.2-0.9.1-fabric
|
||||
iris_version=1.11.1+26.2-fabric
|
||||
immediatelyfast_version=1.16.0+26.2-fabric
|
||||
xaero_minimap_version=fabric-26.2-26.1.3
|
||||
xaero_worldmap_version=fabric-26.2-1.41.1
|
||||
viafabricplus_version=4.6.0
|
||||
entityculling_version=1.10.5
|
||||
BIN
mod/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
mod/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
9
mod/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
9
mod/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
|
||||
networkTimeout=10000
|
||||
retries=0
|
||||
retryBackOffMs=500
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
14
mod/lombok.config
Normal file
14
mod/lombok.config
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
config.stopBubbling = true
|
||||
|
||||
lombok.addLombokGeneratedAnnotation = true
|
||||
lombok.anyConstructor.addConstructorProperties = true
|
||||
|
||||
lombok.data.flagUsage = error
|
||||
lombok.var.flagUsage = error
|
||||
lombok.val.flagUsage = warning
|
||||
lombok.sneakyThrows.flagUsage = error
|
||||
lombok.cleanup.flagUsage = error
|
||||
lombok.experimental.flagUsage = warning
|
||||
|
||||
lombok.equalsAndHashCode.callSuper = warn
|
||||
lombok.toString.callSuper = warn
|
||||
9
mod/settings.gradle
Normal file
9
mod/settings.gradle
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
pluginManagement {
|
||||
repositories {
|
||||
maven {
|
||||
name = 'Fabric'
|
||||
url = 'https://maven.fabricmc.net/'
|
||||
}
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,301 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.features.command.impl;
|
||||
|
||||
import dev.loki.lovisual.features.command.ClientCommand;
|
||||
import dev.loki.lovisual.features.command.CommandContext;
|
||||
import dev.loki.lovisual.features.command.CommandInfo;
|
||||
import dev.loki.lovisual.features.command.CommandOutput;
|
||||
import dev.loki.lovisual.render.engine.profiler.FrameStutterProfiler;
|
||||
import dev.loki.lovisual.render.engine.profiler.JfrProfiler;
|
||||
import dev.loki.lovisual.render.engine.profiler.ProfilerSettings;
|
||||
import dev.loki.lovisual.render.engine.profiler.TracyProfiler;
|
||||
import dev.loki.lovisual.Lifecycle;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@CommandInfo(
|
||||
id = "profiler",
|
||||
aliases = "prof",
|
||||
usage = "@profiler [2d|3d|all|sample|stutter|tracy|jfr] ...",
|
||||
descriptionKey = "command.profiler.description"
|
||||
)
|
||||
public final class ProfilerCommand implements ClientCommand {
|
||||
|
||||
@Override
|
||||
public boolean isAvailable() {
|
||||
return Lifecycle.isActive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean execute(CommandContext ctx) {
|
||||
if (!Lifecycle.isActive()) {
|
||||
CommandOutput.send("Profiler: disabled until client is active.");
|
||||
return true;
|
||||
}
|
||||
String target = ctx.arg(0);
|
||||
if (target == null
|
||||
|| !(target.equalsIgnoreCase("2d")
|
||||
|| target.equalsIgnoreCase("3d")
|
||||
|| target.equalsIgnoreCase("all")
|
||||
|| target.equalsIgnoreCase("sample")
|
||||
|| target.equalsIgnoreCase("stutter")
|
||||
|| target.equalsIgnoreCase("tracy")
|
||||
|| target.equalsIgnoreCase("jfr"))) {
|
||||
CommandOutput.send("Usage: " + metadata().usage());
|
||||
return true;
|
||||
}
|
||||
|
||||
String mode = ctx.arg(1);
|
||||
String targetArg = ctx.arg(2);
|
||||
String detailArg = ctx.arg(3);
|
||||
if (target.equalsIgnoreCase("jfr")) {
|
||||
return executeJfr(mode, targetArg);
|
||||
}
|
||||
if (target.equalsIgnoreCase("stutter")) {
|
||||
return executeStutter(mode, targetArg, detailArg);
|
||||
}
|
||||
if (target.equalsIgnoreCase("tracy")) {
|
||||
boolean enable = mode == null || mode.equalsIgnoreCase("on");
|
||||
if (mode != null && !mode.equalsIgnoreCase("on") && !mode.equalsIgnoreCase("off")) {
|
||||
CommandOutput.send("Usage: " + metadata().usage());
|
||||
return true;
|
||||
}
|
||||
boolean active = TracyProfiler.setEnabled(enable);
|
||||
if (!enable) {
|
||||
CommandOutput.send("Profiler tracy: off");
|
||||
} else if (active) {
|
||||
CommandOutput.send("Profiler tracy: on (streams to external Tracy viewer, not latest.log)");
|
||||
} else {
|
||||
CommandOutput.send("Profiler tracy: unavailable");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (mode == null) {
|
||||
mode = "chat";
|
||||
}
|
||||
|
||||
ProfilerSettings.OutputMode modeOutput = ProfilerSettings.parseOutput(mode);
|
||||
ProfilerSettings.SampleTarget modeTarget = ProfilerSettings.parseTarget(mode);
|
||||
ProfilerSettings.SampleTarget targetTarget = ProfilerSettings.parseTarget(targetArg);
|
||||
ProfilerSettings.OutputMode targetOutput = ProfilerSettings.parseOutput(targetArg);
|
||||
Boolean detailMode = parseDetailMode(detailArg);
|
||||
|
||||
boolean modeIsOutput = modeOutput != null;
|
||||
boolean modeIsTarget = modeTarget != null;
|
||||
|
||||
if (!modeIsOutput && !modeIsTarget) {
|
||||
CommandOutput.send("Usage: " + metadata().usage());
|
||||
return true;
|
||||
}
|
||||
|
||||
String t = target.toLowerCase();
|
||||
if (!t.equals("sample") && !modeIsOutput) {
|
||||
CommandOutput.send("Usage: " + metadata().usage());
|
||||
return true;
|
||||
}
|
||||
if (t.equals("2d")) {
|
||||
ProfilerSettings.setOutput2d(modeOutput);
|
||||
} else if (t.equals("3d")) {
|
||||
ProfilerSettings.setOutput3d(modeOutput);
|
||||
} else if (t.equals("sample")) {
|
||||
if (modeIsTarget) {
|
||||
ProfilerSettings.setSampleTarget(modeTarget);
|
||||
if (targetOutput != null) {
|
||||
ProfilerSettings.setSampleOutput(targetOutput);
|
||||
modeOutput = targetOutput;
|
||||
} else {
|
||||
ProfilerSettings.setSampleOutput(ProfilerSettings.OutputMode.CHAT);
|
||||
modeOutput = ProfilerSettings.OutputMode.CHAT;
|
||||
}
|
||||
} else {
|
||||
ProfilerSettings.setSampleOutput(modeOutput);
|
||||
}
|
||||
if (targetTarget != null) {
|
||||
ProfilerSettings.setSampleTarget(targetTarget);
|
||||
}
|
||||
if (detailMode != null) {
|
||||
ProfilerSettings.setSampleDetailedStacks(detailMode);
|
||||
}
|
||||
} else {
|
||||
ProfilerSettings.setOutput2d(modeOutput);
|
||||
ProfilerSettings.setOutput3d(modeOutput);
|
||||
}
|
||||
if (t.equals("sample")) {
|
||||
CommandOutput.send("Profiler sample output: " + modeOutput.name().toLowerCase()
|
||||
+ " (target " + ProfilerSettings.formatTarget(ProfilerSettings.getSampleTarget())
|
||||
+ ", stacks " + (ProfilerSettings.isSampleDetailedStacks() ? "on" : "off") + ")");
|
||||
} else {
|
||||
CommandOutput.send("Profiler " + t + " output: " + modeOutput.name().toLowerCase());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> suggest(CommandContext ctx, int argIndex, String token) {
|
||||
if (argIndex == 1) {
|
||||
return matchToken(token, List.of("2d", "3d", "all", "sample", "stutter", "tracy", "jfr"));
|
||||
}
|
||||
if (argIndex == 2) {
|
||||
String t = ctx.arg(0);
|
||||
if (t != null && (t.equalsIgnoreCase("sample") || t.equalsIgnoreCase("stutter"))) {
|
||||
return matchToken(token, List.of("off", "log", "chat", "2d", "3d", "all"));
|
||||
}
|
||||
if (t != null && t.equalsIgnoreCase("tracy")) {
|
||||
return matchToken(token, List.of("on", "off"));
|
||||
}
|
||||
if (t != null && t.equalsIgnoreCase("jfr")) {
|
||||
return matchToken(token, List.of("start", "stop", "dump", "status"));
|
||||
}
|
||||
return matchToken(token, List.of("off", "log", "chat"));
|
||||
}
|
||||
if (argIndex == 3) {
|
||||
String t = ctx.arg(0);
|
||||
if (t != null && t.equalsIgnoreCase("sample")) {
|
||||
return matchToken(token, List.of("2d", "3d", "all"));
|
||||
}
|
||||
if (t != null && t.equalsIgnoreCase("jfr")) {
|
||||
String action = ctx.arg(1);
|
||||
if (action == null || action.equalsIgnoreCase("start")) {
|
||||
return matchToken(token, List.of("gc", "alloc", "full"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (argIndex == 4) {
|
||||
String t = ctx.arg(0);
|
||||
if (t != null && t.equalsIgnoreCase("sample")) {
|
||||
return matchToken(token, List.of("stacks", "nostacks"));
|
||||
}
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private boolean executeStutter(String mode, String thresholdArg, String sampleArg) {
|
||||
if (mode == null || mode.equalsIgnoreCase("status")) {
|
||||
CommandOutput.send(FrameStutterProfiler.statusLine());
|
||||
return true;
|
||||
}
|
||||
ProfilerSettings.OutputMode output = ProfilerSettings.parseOutput(mode);
|
||||
if (output == null) {
|
||||
CommandOutput.send("Profiler stutter usage: @profiler stutter [off|log|chat|status] [thresholdMs] [sampleMs]");
|
||||
return true;
|
||||
}
|
||||
double thresholdMs = parseDouble(thresholdArg, 35.0);
|
||||
double sampleMs = parseDouble(sampleArg, 2.0);
|
||||
FrameStutterProfiler.configure(output, thresholdMs, sampleMs);
|
||||
CommandOutput.send(FrameStutterProfiler.statusLine());
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean executeJfr(String action, String presetArg) {
|
||||
if (action == null || action.equalsIgnoreCase("status")) {
|
||||
CommandOutput.send(JfrProfiler.statusLine());
|
||||
return true;
|
||||
}
|
||||
if (action.equalsIgnoreCase("start")) {
|
||||
JfrProfiler.Preset preset = JfrProfiler.Preset.parse(presetArg);
|
||||
if (preset == null) {
|
||||
CommandOutput.send("Profiler JFR usage: @profiler jfr start [gc|alloc|full]");
|
||||
return true;
|
||||
}
|
||||
JfrProfiler.StartResult result = JfrProfiler.start(preset);
|
||||
if (result.started()) {
|
||||
CommandOutput.send("Profiler JFR: started " + preset.getId() + " -> " + absolute(result.path()));
|
||||
return true;
|
||||
}
|
||||
if (result.alreadyRunning()) {
|
||||
CommandOutput.send("Profiler JFR: already running ("
|
||||
+ result.preset().getId() + ", file " + absolute(result.path()) + ")");
|
||||
return true;
|
||||
}
|
||||
CommandOutput.send("Profiler JFR: unavailable"
|
||||
+ (result.error() == null ? "" : " (" + result.error() + ")"));
|
||||
return true;
|
||||
}
|
||||
if (action.equalsIgnoreCase("dump")) {
|
||||
JfrProfiler.DumpResult result = JfrProfiler.dumpSnapshot();
|
||||
if (result.dumped()) {
|
||||
CommandOutput.send("Profiler JFR: snapshot -> " + absolute(result.path()));
|
||||
return true;
|
||||
}
|
||||
if (result.notRunning()) {
|
||||
CommandOutput.send("Profiler JFR: not running");
|
||||
return true;
|
||||
}
|
||||
CommandOutput.send("Profiler JFR: snapshot failed"
|
||||
+ (result.error() == null ? "" : " (" + result.error() + ")"));
|
||||
return true;
|
||||
}
|
||||
if (action.equalsIgnoreCase("stop")) {
|
||||
JfrProfiler.StopResult result = JfrProfiler.stop();
|
||||
if (result.stopped()) {
|
||||
long seconds = result.startedAt() == null
|
||||
? 0L
|
||||
: Math.max(0L, Duration.between(result.startedAt(), Instant.now()).toSeconds());
|
||||
CommandOutput.send("Profiler JFR: saved " + result.preset().getId()
|
||||
+ " (" + formatDuration(seconds) + ") -> " + absolute(result.path()));
|
||||
return true;
|
||||
}
|
||||
if (result.notRunning()) {
|
||||
CommandOutput.send("Profiler JFR: not running");
|
||||
return true;
|
||||
}
|
||||
CommandOutput.send("Profiler JFR: stop failed"
|
||||
+ (result.error() == null ? "" : " (" + result.error() + ")"));
|
||||
return true;
|
||||
}
|
||||
CommandOutput.send("Profiler JFR usage: @profiler jfr [start|stop|dump|status] [gc|alloc|full]");
|
||||
return true;
|
||||
}
|
||||
|
||||
private Boolean parseDetailMode(String raw) {
|
||||
if (raw == null) return null;
|
||||
return switch (raw.toLowerCase()) {
|
||||
case "stacks", "stack", "detail", "detailed" -> Boolean.TRUE;
|
||||
case "nostacks", "nostack", "basic", "light" -> Boolean.FALSE;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private double parseDouble(String raw, double fallback) {
|
||||
if (raw == null || raw.isBlank()) return fallback;
|
||||
try {
|
||||
double value = Double.parseDouble(raw.trim());
|
||||
return Double.isFinite(value) ? value : fallback;
|
||||
} catch (NumberFormatException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> matchToken(String token, List<String> options) {
|
||||
String lower = token == null ? "" : token.toLowerCase();
|
||||
List<String> out = new java.util.ArrayList<>();
|
||||
for (String opt : options) {
|
||||
if (lower.isEmpty() || opt.startsWith(lower)) {
|
||||
out.add(opt);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private String absolute(Path path) {
|
||||
return path == null ? "<unknown>" : path.toAbsolutePath().toString();
|
||||
}
|
||||
|
||||
private String formatDuration(long totalSeconds) {
|
||||
long minutes = totalSeconds / 60L;
|
||||
long seconds = totalSeconds % 60L;
|
||||
if (minutes <= 0L) {
|
||||
return seconds + "s";
|
||||
}
|
||||
return minutes + "m " + seconds + "s";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package dev.loki.lovisual.mixins;
|
||||
|
||||
import net.minecraft.util.profiling.InactiveProfiler;
|
||||
import net.minecraft.util.profiling.Profiler;
|
||||
import net.minecraft.util.profiling.ProfilerFiller;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
import dev.loki.lovisual.render.engine.profiler.DevTracyProfiler;
|
||||
|
||||
@Mixin(Profiler.class)
|
||||
public abstract class ProfilersMixin {
|
||||
|
||||
@Inject(method = "getDefaultFiller", at = @At("HEAD"), cancellable = true)
|
||||
private static void lovisual$limitVanillaTracyToRenderThread(CallbackInfoReturnable<ProfilerFiller> cir) {
|
||||
if (!DevTracyProfiler.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (DevTracyProfiler.shouldTraceCurrentThread()) {
|
||||
return;
|
||||
}
|
||||
cir.setReturnValue(InactiveProfiler.INSTANCE);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,494 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import com.sun.management.GarbageCollectionNotificationInfo;
|
||||
import com.sun.management.GcInfo;
|
||||
import dev.loki.lovisual.util.screen.ClientScreen;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
|
||||
|
||||
import javax.management.Notification;
|
||||
import javax.management.NotificationEmitter;
|
||||
import javax.management.openmbean.CompositeData;
|
||||
import java.lang.management.GarbageCollectorMXBean;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.MemoryUsage;
|
||||
import java.util.*;
|
||||
|
||||
public enum DevFrameStutterProfiler {
|
||||
;
|
||||
private static final long DEFAULT_THRESHOLD_NS = 35_000_000L;
|
||||
private static final long DEFAULT_SAMPLE_INTERVAL_NS = 2_000_000L;
|
||||
private static final long GC_CORRELATION_WINDOW_NS = 75_000_000L;
|
||||
private static final int MAX_STACK_FRAMES = 6;
|
||||
private static final int MAX_SAMPLES = 2048;
|
||||
private static final int MAX_GC_EVENTS = 64;
|
||||
private static final int TOP_STACKS = 8;
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
private static final Sample[] SAMPLES = new Sample[MAX_SAMPLES];
|
||||
private static final GcEvent[] GC_EVENTS = new GcEvent[MAX_GC_EVENTS];
|
||||
|
||||
private static volatile ProfilerSettings.OutputMode output = ProfilerSettings.OutputMode.OFF;
|
||||
private static volatile long thresholdNs = DEFAULT_THRESHOLD_NS;
|
||||
private static volatile long sampleIntervalNs = DEFAULT_SAMPLE_INTERVAL_NS;
|
||||
private static volatile Thread renderThread;
|
||||
private static volatile Thread samplerThread;
|
||||
private static volatile boolean running;
|
||||
private static volatile boolean gcListenerInstalled;
|
||||
|
||||
private static int sampleCursor;
|
||||
private static int sampleCount;
|
||||
private static int gcCursor;
|
||||
private static int gcCount;
|
||||
private static long lastPresentedNs;
|
||||
private static long lastLoggedNs;
|
||||
|
||||
public static void configure(ProfilerSettings.OutputMode mode, double thresholdMs, double sampleMs) {
|
||||
output = mode == null ? ProfilerSettings.OutputMode.OFF : mode;
|
||||
thresholdNs = clampMs(thresholdMs, 1.0, 5000.0, DEFAULT_THRESHOLD_NS);
|
||||
sampleIntervalNs = clampMs(sampleMs, 1.0, 100.0, DEFAULT_SAMPLE_INTERVAL_NS);
|
||||
if (output == ProfilerSettings.OutputMode.OFF) {
|
||||
stopSampler();
|
||||
synchronized (LOCK) {
|
||||
sampleCursor = 0;
|
||||
sampleCount = 0;
|
||||
lastPresentedNs = 0L;
|
||||
lastLoggedNs = 0L;
|
||||
}
|
||||
return;
|
||||
}
|
||||
installGcListener();
|
||||
ensureSampler();
|
||||
}
|
||||
|
||||
public static String statusLine() {
|
||||
if (output == ProfilerSettings.OutputMode.OFF) {
|
||||
return "Profiler stutter: off";
|
||||
}
|
||||
return String.format(Locale.ROOT,
|
||||
"Profiler stutter: %s (threshold %.1f ms, sample %.1f ms)",
|
||||
output.name().toLowerCase(Locale.ROOT),
|
||||
thresholdNs / 1_000_000.0,
|
||||
sampleIntervalNs / 1_000_000.0);
|
||||
}
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return output != ProfilerSettings.OutputMode.OFF;
|
||||
}
|
||||
|
||||
public static void onFramePresented(RhiStatsSnapshot rhi,
|
||||
UniformAllocatorStatsSnapshot uniforms,
|
||||
RenderResourceStatsSnapshot resources) {
|
||||
try {
|
||||
if (!isEnabled()) return;
|
||||
|
||||
renderThread = Thread.currentThread();
|
||||
ensureSampler();
|
||||
|
||||
long now = System.nanoTime();
|
||||
long previous;
|
||||
synchronized (LOCK) {
|
||||
previous = lastPresentedNs;
|
||||
lastPresentedNs = now;
|
||||
}
|
||||
if (previous == 0L) return;
|
||||
|
||||
long elapsedNs = now - previous;
|
||||
if (elapsedNs < thresholdNs) return;
|
||||
if (now - lastLoggedNs < thresholdNs) return;
|
||||
lastLoggedNs = now;
|
||||
|
||||
List<String> lines = buildReport(previous, now, elapsedNs, rhi, uniforms, resources);
|
||||
emit(lines);
|
||||
} catch (Throwable t) {
|
||||
ProfilerLog.warn("[FrameStutter] disabled after profiler failure: %s",
|
||||
t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
configure(ProfilerSettings.OutputMode.OFF, 0.0, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> buildReport(long frameStartNs,
|
||||
long frameEndNs,
|
||||
long elapsedNs,
|
||||
RhiStatsSnapshot rhi,
|
||||
UniformAllocatorStatsSnapshot uniforms,
|
||||
RenderResourceStatsSnapshot resources) {
|
||||
List<Sample> samples = samplesInWindow(frameStartNs, frameEndNs);
|
||||
List<GcEvent> gcEvents = gcNearWindow(frameStartNs, frameEndNs);
|
||||
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
String screen = mc == null || ClientScreen.current() == null ? "none" : ClientScreen.current().getClass().getSimpleName();
|
||||
String world = mc == null || mc.level == null ? "none" : mc.level.dimension().identifier().toString();
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] frame %.2f ms over %.2f ms, samples %d, screen=%s, world=%s",
|
||||
elapsedNs / 1_000_000.0,
|
||||
thresholdNs / 1_000_000.0,
|
||||
samples.size(),
|
||||
screen,
|
||||
world));
|
||||
|
||||
if (rhi != null) {
|
||||
long uploaded = rhi.uploadedVertexBytes() + rhi.uploadedIndexBytes();
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] rhi draw=%d fs=%d meshUpload=%d/%s copies=%d/%d ringWrap=%d stall=%d fallback=%d backlog=%d",
|
||||
rhi.drawCalls(),
|
||||
rhi.fullscreenPasses(),
|
||||
rhi.meshUploads(),
|
||||
formatBytes(uploaded),
|
||||
rhi.textureFastCopies(),
|
||||
rhi.textureShaderCopies(),
|
||||
rhi.ringWraps(),
|
||||
rhi.ringStalls(),
|
||||
rhi.immediateFallbackUploads(),
|
||||
rhi.dynamicArenaBacklogEvents()));
|
||||
}
|
||||
if (uniforms != null || resources != null) {
|
||||
long uniformWrites = uniforms == null ? 0L : uniforms.writes();
|
||||
long uniformBytes = uniforms == null ? 0L : uniforms.uploadedBytes();
|
||||
int retireBacklog = resources == null ? 0 : resources.retirementBacklog();
|
||||
int leaks = resources == null ? 0 : resources.leakedResources();
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] uniforms writes=%d/%s resourceBacklog=%d leaks=%d",
|
||||
uniformWrites,
|
||||
formatBytes(uniformBytes),
|
||||
retireBacklog,
|
||||
leaks));
|
||||
}
|
||||
|
||||
if (gcEvents.isEmpty()) {
|
||||
lines.add("[FrameStutter] gc nearby: none");
|
||||
} else {
|
||||
for (GcEvent gc : gcEvents) {
|
||||
double relativeEndMs = (gc.endNs - frameStartNs) / 1_000_000.0;
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] gc nearby: %s %s %.2f ms at %+,.2f ms, freed %s",
|
||||
gc.name,
|
||||
gc.cause,
|
||||
(double) gc.durationMs,
|
||||
relativeEndMs,
|
||||
formatBytes(gc.freedBytes)));
|
||||
}
|
||||
}
|
||||
|
||||
appendSampleSummary(lines, samples);
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static void appendSampleSummary(List<String> lines, List<Sample> samples) {
|
||||
if (samples.isEmpty()) {
|
||||
lines.add("[FrameStutter] sample top: none");
|
||||
return;
|
||||
}
|
||||
Map<String, Integer> counts = new HashMap<>();
|
||||
int glWait = 0;
|
||||
int glUpload = 0;
|
||||
int glDraw = 0;
|
||||
int glState = 0;
|
||||
for (Sample sample : samples) {
|
||||
counts.merge(sample.stack, 1, Integer::sum);
|
||||
if (sample.stack.startsWith("GL WAIT:")) {
|
||||
glWait++;
|
||||
} else if (sample.stack.startsWith("GL UPLOAD:")) {
|
||||
glUpload++;
|
||||
} else if (sample.stack.startsWith("GL DRAW:")) {
|
||||
glDraw++;
|
||||
} else if (sample.stack.startsWith("GL STATE:")) {
|
||||
glState++;
|
||||
}
|
||||
}
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] gl samples wait/upload/draw/state=%d/%d/%d/%d",
|
||||
glWait,
|
||||
glUpload,
|
||||
glDraw,
|
||||
glState));
|
||||
|
||||
List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());
|
||||
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
|
||||
lines.add("[FrameStutter] sample top:");
|
||||
int top = Math.min(TOP_STACKS, entries.size());
|
||||
for (int i = 0; i < top; i++) {
|
||||
Map.Entry<String, Integer> entry = entries.get(i);
|
||||
double pct = entry.getValue() * 100.0 / samples.size();
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] %d) %s (%d, %.1f%%)",
|
||||
i + 1,
|
||||
entry.getKey(),
|
||||
entry.getValue(),
|
||||
pct));
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Sample> samplesInWindow(long startNs, long endNs) {
|
||||
List<Sample> out = new ArrayList<>();
|
||||
synchronized (LOCK) {
|
||||
for (int i = 0; i < sampleCount; i++) {
|
||||
Sample sample = SAMPLES[i];
|
||||
if (sample != null && sample.timeNs >= startNs && sample.timeNs <= endNs) {
|
||||
out.add(sample);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort((a, b) -> Long.compare(a.timeNs, b.timeNs));
|
||||
return out;
|
||||
}
|
||||
|
||||
private static List<GcEvent> gcNearWindow(long startNs, long endNs) {
|
||||
long from = startNs - GC_CORRELATION_WINDOW_NS;
|
||||
long to = endNs + GC_CORRELATION_WINDOW_NS;
|
||||
List<GcEvent> out = new ArrayList<>();
|
||||
synchronized (LOCK) {
|
||||
for (int i = 0; i < gcCount; i++) {
|
||||
GcEvent event = GC_EVENTS[i];
|
||||
if (event != null && event.endNs >= from && event.endNs <= to) {
|
||||
out.add(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort((a, b) -> Long.compare(a.endNs, b.endNs));
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void ensureSampler() {
|
||||
if (running || output == ProfilerSettings.OutputMode.OFF) return;
|
||||
running = true;
|
||||
samplerThread = new Thread(DevFrameStutterProfiler::sampleLoop, "LoVisual-DevFrameStutterProfiler");
|
||||
samplerThread.setDaemon(true);
|
||||
samplerThread.start();
|
||||
}
|
||||
|
||||
private static void stopSampler() {
|
||||
running = false;
|
||||
Thread thread = samplerThread;
|
||||
samplerThread = null;
|
||||
if (thread != null) {
|
||||
thread.interrupt();
|
||||
}
|
||||
renderThread = null;
|
||||
}
|
||||
|
||||
private static void sampleLoop() {
|
||||
long lastSampleNs = 0L;
|
||||
while (running) {
|
||||
if (output == ProfilerSettings.OutputMode.OFF) {
|
||||
sleepMs(20L);
|
||||
continue;
|
||||
}
|
||||
Thread target = renderThread;
|
||||
if (target == null) {
|
||||
sleepMs(10L);
|
||||
continue;
|
||||
}
|
||||
long now = System.nanoTime();
|
||||
if (now - lastSampleNs >= sampleIntervalNs) {
|
||||
recordSample(now, target);
|
||||
lastSampleNs = now;
|
||||
}
|
||||
sleepMs(1L);
|
||||
}
|
||||
}
|
||||
|
||||
private static void recordSample(long now, Thread target) {
|
||||
StackTraceElement[] stack = target.getStackTrace();
|
||||
if (stack == null || stack.length == 0) return;
|
||||
String key = buildKey(stack);
|
||||
if (key == null || key.isBlank()) return;
|
||||
synchronized (LOCK) {
|
||||
SAMPLES[sampleCursor] = new Sample(now, key);
|
||||
sampleCursor = (sampleCursor + 1) % MAX_SAMPLES;
|
||||
if (sampleCount < MAX_SAMPLES) {
|
||||
sampleCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String buildKey(StackTraceElement[] stack) {
|
||||
StringBuilder sb = new StringBuilder(320);
|
||||
String glCat = glCategory(stack);
|
||||
if (glCat != null) {
|
||||
sb.append("GL ").append(glCat).append(": ");
|
||||
}
|
||||
int added = 0;
|
||||
for (StackTraceElement e : stack) {
|
||||
if (added >= MAX_STACK_FRAMES) break;
|
||||
if (isNoise(e)) continue;
|
||||
if (added > 0) sb.append(" <= ");
|
||||
sb.append(formatElement(e));
|
||||
added++;
|
||||
}
|
||||
return added == 0 ? null : sb.toString();
|
||||
}
|
||||
|
||||
private static String glCategory(StackTraceElement[] stack) {
|
||||
for (StackTraceElement e : stack) {
|
||||
String cls = e.getClassName();
|
||||
String method = e.getMethodName();
|
||||
if (!isGlFrame(cls)) continue;
|
||||
if (method == null) continue;
|
||||
if (method.equals("glfwSwapBuffers")
|
||||
|| method.equals("glClientWaitSync")
|
||||
|| method.equals("nglClientWaitSync")
|
||||
|| method.equals("glWaitSync")
|
||||
|| method.equals("glFinish")) {
|
||||
return "WAIT";
|
||||
}
|
||||
if (method.startsWith("glDraw") || method.startsWith("glMultiDraw")) {
|
||||
return "DRAW";
|
||||
}
|
||||
if (method.contains("BufferSubData")
|
||||
|| method.contains("BufferData")
|
||||
|| method.contains("TexImage")
|
||||
|| method.contains("TexSubImage")
|
||||
|| method.contains("FlushMapped")
|
||||
|| method.contains("MapBuffer")
|
||||
|| method.contains("MapBufferRange")
|
||||
|| method.contains("UnmapBuffer")) {
|
||||
return "UPLOAD";
|
||||
}
|
||||
if (method.startsWith("glUseProgram")
|
||||
|| method.startsWith("glBind")
|
||||
|| method.startsWith("glTexParameter")
|
||||
|| method.startsWith("glBlend")
|
||||
|| method.startsWith("glEnable")
|
||||
|| method.startsWith("glDisable")
|
||||
|| method.startsWith("glDepth")
|
||||
|| method.startsWith("glColorMask")
|
||||
|| method.startsWith("glViewport")
|
||||
|| method.startsWith("glScissor")
|
||||
|| method.startsWith("glActiveTexture")
|
||||
|| method.startsWith("glUniform")
|
||||
|| method.startsWith("glVertexAttrib")) {
|
||||
return "STATE";
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isGlFrame(String cls) {
|
||||
return cls != null
|
||||
&& (cls.startsWith("org.lwjgl.opengl.")
|
||||
|| cls.startsWith("org.lwjgl.glfw.")
|
||||
|| cls.startsWith("com.mojang.blaze3d.platform.")
|
||||
|| cls.startsWith("com.mojang.blaze3d.systems."));
|
||||
}
|
||||
|
||||
private static boolean isNoise(StackTraceElement e) {
|
||||
String cls = e.getClassName();
|
||||
return cls.startsWith("java.lang.Thread")
|
||||
|| cls.startsWith("jdk.internal")
|
||||
|| cls.startsWith("sun.")
|
||||
|| cls.startsWith("dev.loki.lovisual.render.engine.profiler.DevFrameStutterProfiler");
|
||||
}
|
||||
|
||||
private static String formatElement(StackTraceElement e) {
|
||||
String file = e.getFileName() == null ? "Unknown" : e.getFileName();
|
||||
return e.getClassName() + "." + e.getMethodName() + "(" + file + ":" + e.getLineNumber() + ")";
|
||||
}
|
||||
|
||||
private static void installGcListener() {
|
||||
if (gcListenerInstalled) return;
|
||||
synchronized (LOCK) {
|
||||
if (gcListenerInstalled) return;
|
||||
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
|
||||
if (bean instanceof NotificationEmitter emitter) {
|
||||
emitter.addNotificationListener(DevFrameStutterProfiler::onGcNotification, null, null);
|
||||
}
|
||||
}
|
||||
gcListenerInstalled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void onGcNotification(Notification notification, Object handback) {
|
||||
if (output == ProfilerSettings.OutputMode.OFF) return;
|
||||
if (!GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION.equals(notification.getType())) return;
|
||||
Object data = notification.getUserData();
|
||||
if (!(data instanceof CompositeData compositeData)) return;
|
||||
try {
|
||||
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from(compositeData);
|
||||
GcInfo gcInfo = info.getGcInfo();
|
||||
long freed = usedBefore(gcInfo) - usedAfter(gcInfo);
|
||||
GcEvent event = new GcEvent(
|
||||
System.nanoTime(),
|
||||
info.getGcName(),
|
||||
info.getGcCause(),
|
||||
Math.max(0L, gcInfo.getDuration()),
|
||||
Math.max(0L, freed));
|
||||
synchronized (LOCK) {
|
||||
GC_EVENTS[gcCursor] = event;
|
||||
gcCursor = (gcCursor + 1) % MAX_GC_EVENTS;
|
||||
if (gcCount < MAX_GC_EVENTS) {
|
||||
gcCount++;
|
||||
}
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private static long usedBefore(GcInfo info) {
|
||||
return used(info == null ? null : info.getMemoryUsageBeforeGc());
|
||||
}
|
||||
|
||||
private static long usedAfter(GcInfo info) {
|
||||
return used(info == null ? null : info.getMemoryUsageAfterGc());
|
||||
}
|
||||
|
||||
private static long used(Map<String, MemoryUsage> usage) {
|
||||
if (usage == null || usage.isEmpty()) return 0L;
|
||||
long total = 0L;
|
||||
for (MemoryUsage value : usage.values()) {
|
||||
if (value != null && value.getUsed() > 0L) {
|
||||
total += value.getUsed();
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private static void emit(List<String> lines) {
|
||||
ProfilerSettings.OutputMode mode = output;
|
||||
if (mode == ProfilerSettings.OutputMode.OFF || lines == null || lines.isEmpty()) return;
|
||||
if (mode == ProfilerSettings.OutputMode.LOG) {
|
||||
for (String line : lines) {
|
||||
ProfilerLog.info("%s", line);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (mode == ProfilerSettings.OutputMode.CHAT) {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.gui == null) return;
|
||||
for (String line : lines) {
|
||||
mc.gui.hud.getChat().addClientSystemMessage(Component.literal(line));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static long clampMs(double valueMs, double minMs, double maxMs, long fallbackNs) {
|
||||
if (!Double.isFinite(valueMs) || valueMs <= 0.0) return fallbackNs;
|
||||
double clamped = Math.max(minMs, Math.min(maxMs, valueMs));
|
||||
return (long) (clamped * 1_000_000.0);
|
||||
}
|
||||
|
||||
private static String formatBytes(long bytes) {
|
||||
if (bytes < 1024L) return bytes + " B";
|
||||
double kb = bytes / 1024.0;
|
||||
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
|
||||
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
|
||||
}
|
||||
|
||||
private static void sleepMs(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private record Sample(long timeNs, String stack) {
|
||||
}
|
||||
|
||||
private record GcEvent(long endNs, String name, String cause, long durationMs, long freedBytes) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,340 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public enum DevGlSyncTracker {
|
||||
;
|
||||
|
||||
private static final int MAX_FENCES = 512;
|
||||
private static final int TOP_PHASES = 4;
|
||||
private static final int TOP_STACKS = 3;
|
||||
private static final int MAX_STACK_FRAMES = 8;
|
||||
private static final int MAX_SLOW_WAITS = 3;
|
||||
private static final long SLOW_WAIT_THRESHOLD_NS = 1_000_000L;
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
private static final LinkedHashMap<Long, FenceInfo> FENCE_INFOS = new LinkedHashMap<>();
|
||||
private static final Map<String, Integer> WAIT_BY_FENCE_PHASE = new HashMap<>();
|
||||
private static final Map<String, Integer> WAIT_BY_WAIT_PHASE = new HashMap<>();
|
||||
private static final Map<String, Long> WAIT_TIME_BY_FENCE_PHASE = new HashMap<>();
|
||||
private static final Map<String, Long> WAIT_TIME_BY_WAIT_PHASE = new HashMap<>();
|
||||
private static final Map<String, StackAggregate> WAIT_BY_CREATE_STACK = new HashMap<>();
|
||||
private static final List<SlowWait> SLOW_WAITS = new ArrayList<>();
|
||||
private static final ThreadLocal<WaitState> WAIT_STATE =
|
||||
ThreadLocal.withInitial(WaitState::new);
|
||||
private static int waitTotal;
|
||||
private static long waitTimeTotalNs;
|
||||
private static int tracyWaitCallsFrame;
|
||||
private static long tracyWaitTimeFrameNs;
|
||||
|
||||
public static void onFence(long sync) {
|
||||
if (!shouldTrackWaits()) return;
|
||||
if (sync == 0L) return;
|
||||
String phase = DevProfilerPhase.current();
|
||||
String createStack = shouldCaptureStacks() ? captureStackTrace() : null;
|
||||
synchronized (LOCK) {
|
||||
FENCE_INFOS.put(sync, new FenceInfo(phase, createStack));
|
||||
trimFences();
|
||||
}
|
||||
}
|
||||
|
||||
public static void onWaitStart(long sync) {
|
||||
if (!shouldTrackWaits()) return;
|
||||
WaitState state = WAIT_STATE.get();
|
||||
state.startNs = System.nanoTime();
|
||||
state.waitPhase = DevProfilerPhase.current();
|
||||
state.waitStack = null;
|
||||
FenceInfo fenceInfo;
|
||||
synchronized (LOCK) {
|
||||
fenceInfo = FENCE_INFOS.remove(sync);
|
||||
}
|
||||
state.fencePhase = fenceInfo == null || fenceInfo.phase == null ? "unknown" : fenceInfo.phase;
|
||||
state.createStack = fenceInfo == null ? null : fenceInfo.createStack;
|
||||
state.active = true;
|
||||
}
|
||||
|
||||
public static void onWaitEnd() {
|
||||
WaitState state = WAIT_STATE.get();
|
||||
if (state == null || !state.active) return;
|
||||
state.active = false;
|
||||
long durationNs = System.nanoTime() - state.startNs;
|
||||
if (durationNs < 0L) durationNs = 0L;
|
||||
if (!shouldTrackWaits()) return;
|
||||
String fencePhase = state.fencePhase == null ? "unknown" : state.fencePhase;
|
||||
String waitPhase = state.waitPhase == null ? "unknown" : state.waitPhase;
|
||||
boolean captureStacks = shouldCaptureStacks();
|
||||
String createStack = captureStacks ? normalizeStack(state.createStack) : null;
|
||||
String waitStack = captureStacks && durationNs >= SLOW_WAIT_THRESHOLD_NS ? captureStackTrace() : null;
|
||||
synchronized (LOCK) {
|
||||
WAIT_BY_FENCE_PHASE.merge(fencePhase, 1, Integer::sum);
|
||||
WAIT_BY_WAIT_PHASE.merge(waitPhase, 1, Integer::sum);
|
||||
WAIT_TIME_BY_FENCE_PHASE.merge(fencePhase, durationNs, Long::sum);
|
||||
WAIT_TIME_BY_WAIT_PHASE.merge(waitPhase, durationNs, Long::sum);
|
||||
if (captureStacks) {
|
||||
StackAggregate aggregate = WAIT_BY_CREATE_STACK.computeIfAbsent(
|
||||
createStack,
|
||||
key -> new StackAggregate(fencePhase, key)
|
||||
);
|
||||
aggregate.count += 1;
|
||||
aggregate.timeNs += durationNs;
|
||||
}
|
||||
if (durationNs >= SLOW_WAIT_THRESHOLD_NS) {
|
||||
recordSlowWait(new SlowWait(
|
||||
durationNs,
|
||||
fencePhase,
|
||||
waitPhase,
|
||||
createStack,
|
||||
captureStacks ? normalizeStack(waitStack) : null
|
||||
));
|
||||
}
|
||||
waitTotal += 1;
|
||||
waitTimeTotalNs += durationNs;
|
||||
tracyWaitCallsFrame += 1;
|
||||
tracyWaitTimeFrameNs += durationNs;
|
||||
}
|
||||
}
|
||||
|
||||
public static void emitTracyFrame() {
|
||||
if (!DevTracyProfiler.isEnabled()) return;
|
||||
int calls;
|
||||
long totalNs;
|
||||
synchronized (LOCK) {
|
||||
calls = tracyWaitCallsFrame;
|
||||
totalNs = tracyWaitTimeFrameNs;
|
||||
tracyWaitCallsFrame = 0;
|
||||
tracyWaitTimeFrameNs = 0L;
|
||||
}
|
||||
DevTracyProfiler.plotGlWait(totalNs / 1_000_000.0, calls);
|
||||
}
|
||||
|
||||
public static List<String> drainLines() {
|
||||
if (!DevSamplingProfiler.isActive()) return List.of();
|
||||
List<String> lines = new ArrayList<>();
|
||||
Map<String, Integer> byFence;
|
||||
Map<String, Integer> byWait;
|
||||
Map<String, Long> timeByFence;
|
||||
Map<String, Long> timeByWait;
|
||||
List<StackAggregate> createStacks;
|
||||
List<SlowWait> slowWaits;
|
||||
int total;
|
||||
long totalNs;
|
||||
synchronized (LOCK) {
|
||||
if (waitTotal == 0) return List.of();
|
||||
total = waitTotal;
|
||||
totalNs = waitTimeTotalNs;
|
||||
byFence = new HashMap<>(WAIT_BY_FENCE_PHASE);
|
||||
byWait = new HashMap<>(WAIT_BY_WAIT_PHASE);
|
||||
timeByFence = new HashMap<>(WAIT_TIME_BY_FENCE_PHASE);
|
||||
timeByWait = new HashMap<>(WAIT_TIME_BY_WAIT_PHASE);
|
||||
createStacks = new ArrayList<>(WAIT_BY_CREATE_STACK.values());
|
||||
slowWaits = new ArrayList<>(SLOW_WAITS);
|
||||
WAIT_BY_FENCE_PHASE.clear();
|
||||
WAIT_BY_WAIT_PHASE.clear();
|
||||
WAIT_TIME_BY_FENCE_PHASE.clear();
|
||||
WAIT_TIME_BY_WAIT_PHASE.clear();
|
||||
WAIT_BY_CREATE_STACK.clear();
|
||||
SLOW_WAITS.clear();
|
||||
waitTotal = 0;
|
||||
waitTimeTotalNs = 0L;
|
||||
}
|
||||
lines.add(String.format("gl wait calls: %d", total));
|
||||
lines.add("gl wait phase (fence): " + formatTop(byFence, total));
|
||||
lines.add("gl wait phase (wait): " + formatTop(byWait, total));
|
||||
if (totalNs > 0L) {
|
||||
lines.add(String.format("gl wait time total: %s", formatDuration(totalNs)));
|
||||
lines.add("gl wait time (fence): " + formatTopTime(timeByFence, totalNs));
|
||||
lines.add("gl wait time (wait): " + formatTopTime(timeByWait, totalNs));
|
||||
}
|
||||
String createStackSummary = formatTopCreateStacks(createStacks, totalNs);
|
||||
if (createStackSummary != null) {
|
||||
lines.add("gl wait source (create): " + createStackSummary);
|
||||
}
|
||||
if (!slowWaits.isEmpty()) {
|
||||
lines.add("gl wait slow traces:");
|
||||
for (int i = 0; i < slowWaits.size(); i++) {
|
||||
SlowWait slow = slowWaits.get(i);
|
||||
lines.add(String.format(
|
||||
" %d) %s fence=%s wait=%s",
|
||||
i + 1,
|
||||
formatDuration(slow.durationNs),
|
||||
slow.fencePhase,
|
||||
slow.waitPhase
|
||||
));
|
||||
if (slow.createStack != null) {
|
||||
lines.add(" create: " + slow.createStack);
|
||||
}
|
||||
if (slow.waitStack != null) {
|
||||
lines.add(" wait: " + slow.waitStack);
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static String formatTop(Map<String, Integer> src, int total) {
|
||||
if (src.isEmpty()) return "n/a";
|
||||
List<Map.Entry<String, Integer>> list = new ArrayList<>(src.entrySet());
|
||||
list.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
|
||||
int top = Math.min(TOP_PHASES, list.size());
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < top; i++) {
|
||||
Map.Entry<String, Integer> e = list.get(i);
|
||||
double pct = total == 0 ? 0.0 : (e.getValue() * 100.0) / total;
|
||||
if (sb.length() > 0) sb.append(", ");
|
||||
sb.append(e.getKey()).append('=').append(e.getValue())
|
||||
.append(String.format(" (%.1f%%)", pct));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String formatTopTime(Map<String, Long> src, long totalNs) {
|
||||
if (src.isEmpty()) return "n/a";
|
||||
List<Map.Entry<String, Long>> list = new ArrayList<>(src.entrySet());
|
||||
list.sort((a, b) -> Long.compare(b.getValue(), a.getValue()));
|
||||
int top = Math.min(TOP_PHASES, list.size());
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < top; i++) {
|
||||
Map.Entry<String, Long> e = list.get(i);
|
||||
double pct = totalNs == 0L ? 0.0 : (e.getValue() * 100.0) / totalNs;
|
||||
if (sb.length() > 0) sb.append(", ");
|
||||
sb.append(e.getKey()).append('=').append(formatDuration(e.getValue()))
|
||||
.append(String.format(" (%.1f%%)", pct));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String formatDuration(long ns) {
|
||||
double ms = ns / 1_000_000.0;
|
||||
return String.format("%.2fms", ms);
|
||||
}
|
||||
|
||||
private static void trimFences() {
|
||||
if (FENCE_INFOS.size() <= MAX_FENCES) return;
|
||||
int toRemove = FENCE_INFOS.size() - MAX_FENCES;
|
||||
var it = FENCE_INFOS.keySet().iterator();
|
||||
while (toRemove > 0 && it.hasNext()) {
|
||||
it.next();
|
||||
it.remove();
|
||||
toRemove--;
|
||||
}
|
||||
}
|
||||
|
||||
private static String formatTopCreateStacks(List<StackAggregate> stacks, long totalNs) {
|
||||
if (stacks == null || stacks.isEmpty()) return null;
|
||||
stacks.sort((a, b) -> Long.compare(b.timeNs, a.timeNs));
|
||||
int top = Math.min(TOP_STACKS, stacks.size());
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < top; i++) {
|
||||
StackAggregate aggregate = stacks.get(i);
|
||||
double pct = totalNs == 0L ? 0.0 : (aggregate.timeNs * 100.0) / totalNs;
|
||||
if (sb.length() > 0) sb.append(" | ");
|
||||
sb.append(aggregate.fencePhase)
|
||||
.append('=')
|
||||
.append(formatDuration(aggregate.timeNs))
|
||||
.append(" x")
|
||||
.append(aggregate.count)
|
||||
.append(String.format(" (%.1f%%)", pct))
|
||||
.append(" :: ")
|
||||
.append(aggregate.createStack);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static void recordSlowWait(SlowWait slowWait) {
|
||||
SLOW_WAITS.add(slowWait);
|
||||
SLOW_WAITS.sort((a, b) -> Long.compare(b.durationNs, a.durationNs));
|
||||
while (SLOW_WAITS.size() > MAX_SLOW_WAITS) {
|
||||
SLOW_WAITS.remove(SLOW_WAITS.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
private static String captureStackTrace() {
|
||||
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
|
||||
StringBuilder sb = new StringBuilder(256);
|
||||
int added = 0;
|
||||
for (StackTraceElement e : stack) {
|
||||
if (added >= MAX_STACK_FRAMES) break;
|
||||
if (isStackNoise(e)) continue;
|
||||
if (added > 0) sb.append(" <= ");
|
||||
sb.append(formatElement(e));
|
||||
added++;
|
||||
}
|
||||
return added == 0 ? "unknown" : sb.toString();
|
||||
}
|
||||
|
||||
private static String normalizeStack(String stack) {
|
||||
return stack == null || stack.isBlank() ? "unknown" : stack;
|
||||
}
|
||||
|
||||
private static boolean shouldCaptureStacks() {
|
||||
return ProfilerSettings.isSampleDetailedStacks();
|
||||
}
|
||||
|
||||
private static boolean shouldTrackWaits() {
|
||||
return DevSamplingProfiler.isActive() || DevTracyProfiler.isEnabled();
|
||||
}
|
||||
|
||||
private static boolean isStackNoise(StackTraceElement e) {
|
||||
String cls = e.getClassName();
|
||||
String method = e.getMethodName();
|
||||
return cls.equals(Thread.class.getName())
|
||||
|| cls.startsWith("java.lang.Thread")
|
||||
|| cls.startsWith("jdk.internal")
|
||||
|| cls.startsWith("sun.")
|
||||
|| cls.startsWith("org.lwjgl.opengl.GL")
|
||||
|| cls.startsWith("org.lwjgl.system.JNI")
|
||||
|| cls.equals(DevGlSyncTracker.class.getName())
|
||||
|| cls.equals("dev.loki.lovisual.mixins.GlStateManagerMixin")
|
||||
|| (cls.equals("com.mojang.blaze3d.opengl.GlStateManager")
|
||||
&& ("_glFenceSync".equals(method) || "_glClientWaitSync".equals(method)));
|
||||
}
|
||||
|
||||
private static String formatElement(StackTraceElement e) {
|
||||
String cls = e.getClassName();
|
||||
int idx = cls.lastIndexOf('.');
|
||||
String simple = idx >= 0 ? cls.substring(idx + 1) : cls;
|
||||
return simple + "." + e.getMethodName() + "(" + e.getFileName() + ":" + e.getLineNumber() + ")";
|
||||
}
|
||||
|
||||
public static void reset() {
|
||||
synchronized (LOCK) {
|
||||
FENCE_INFOS.clear();
|
||||
WAIT_BY_FENCE_PHASE.clear();
|
||||
WAIT_BY_WAIT_PHASE.clear();
|
||||
WAIT_TIME_BY_FENCE_PHASE.clear();
|
||||
WAIT_TIME_BY_WAIT_PHASE.clear();
|
||||
WAIT_BY_CREATE_STACK.clear();
|
||||
SLOW_WAITS.clear();
|
||||
waitTotal = 0;
|
||||
waitTimeTotalNs = 0L;
|
||||
}
|
||||
}
|
||||
|
||||
private record FenceInfo(String phase, String createStack) {
|
||||
}
|
||||
|
||||
private static final class StackAggregate {
|
||||
final String fencePhase;
|
||||
final String createStack;
|
||||
int count;
|
||||
long timeNs;
|
||||
|
||||
StackAggregate(String fencePhase, String createStack) {
|
||||
this.fencePhase = fencePhase;
|
||||
this.createStack = createStack;
|
||||
}
|
||||
}
|
||||
|
||||
private record SlowWait(long durationNs, String fencePhase, String waitPhase, String createStack,
|
||||
String waitStack) {
|
||||
}
|
||||
|
||||
private static final class WaitState {
|
||||
long startNs;
|
||||
String fencePhase;
|
||||
String waitPhase;
|
||||
String createStack;
|
||||
String waitStack;
|
||||
boolean active;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,253 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import jdk.jfr.EventSettings;
|
||||
import jdk.jfr.Recording;
|
||||
import net.minecraft.client.Minecraft;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public enum DevJfrProfiler {
|
||||
;
|
||||
|
||||
private static final DateTimeFormatter FILE_TIME =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
|
||||
|
||||
private static Recording recording;
|
||||
private static Preset activePreset;
|
||||
private static Instant startedAt;
|
||||
private static Path outputPath;
|
||||
|
||||
public static synchronized StartResult start(Preset preset) {
|
||||
if (recording != null) {
|
||||
return StartResult.alreadyRunning(activePreset, outputPath, startedAt);
|
||||
}
|
||||
try {
|
||||
Path dir = ensureOutputDirectory();
|
||||
Path file = dir.resolve(defaultFileName(preset, false));
|
||||
|
||||
Recording next = new Recording();
|
||||
next.setName("LoVisual " + preset.getId());
|
||||
next.setToDisk(true);
|
||||
next.setDumpOnExit(false);
|
||||
configure(next, preset);
|
||||
next.start();
|
||||
|
||||
recording = next;
|
||||
activePreset = preset;
|
||||
startedAt = Instant.now();
|
||||
outputPath = file;
|
||||
|
||||
ProfilerLog.info("JFR started (%s) -> %s", preset.getId(), file.toAbsolutePath());
|
||||
return StartResult.started(preset, file, startedAt);
|
||||
} catch (Throwable t) {
|
||||
ProfilerLog.warn("JFR unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
return StartResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized DumpResult dumpSnapshot() {
|
||||
if (recording == null) {
|
||||
return DumpResult.notRunningResult();
|
||||
}
|
||||
try {
|
||||
Path dir = ensureOutputDirectory();
|
||||
Path snapshot = dir.resolve(defaultFileName(activePreset, true));
|
||||
recording.dump(snapshot);
|
||||
ProfilerLog.info("JFR snapshot dumped -> %s", snapshot.toAbsolutePath());
|
||||
return DumpResult.dumped(snapshot);
|
||||
} catch (Throwable t) {
|
||||
ProfilerLog.warn("JFR snapshot failed: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
return DumpResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized StopResult stop() {
|
||||
if (recording == null) {
|
||||
return StopResult.notRunningResult();
|
||||
}
|
||||
Recording current = recording;
|
||||
Preset preset = activePreset;
|
||||
Instant started = startedAt;
|
||||
Path destination = outputPath;
|
||||
recording = null;
|
||||
activePreset = null;
|
||||
startedAt = null;
|
||||
outputPath = null;
|
||||
try {
|
||||
current.stop();
|
||||
Files.createDirectories(destination.getParent());
|
||||
current.dump(destination);
|
||||
current.close();
|
||||
ProfilerLog.info("JFR stopped (%s) -> %s", preset.getId(), destination.toAbsolutePath());
|
||||
return StopResult.stopped(preset, destination, started);
|
||||
} catch (Throwable t) {
|
||||
try {
|
||||
current.close();
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
ProfilerLog.warn("JFR stop failed: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
return StopResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized String statusLine() {
|
||||
if (recording == null) {
|
||||
return "Profiler JFR: off";
|
||||
}
|
||||
long seconds = Math.max(0L, Duration.between(startedAt, Instant.now()).toSeconds());
|
||||
return "Profiler JFR: on (" + activePreset.getId()
|
||||
+ ", " + formatDuration(seconds)
|
||||
+ ", file " + outputPath.toAbsolutePath() + ")";
|
||||
}
|
||||
|
||||
private static void configure(Recording recording, Preset preset) {
|
||||
enable(recording, "jdk.GarbageCollection", true, null, null);
|
||||
enable(recording, "jdk.GCHeapSummary", false, null, null);
|
||||
enable(recording, "jdk.MetaspaceSummary", false, null, null);
|
||||
enable(recording, "jdk.CPULoad", false, Duration.ofSeconds(1), null);
|
||||
enable(recording, "jdk.JavaThreadStatistics", false, Duration.ofSeconds(1), null);
|
||||
if (preset.capturesAllocations()) {
|
||||
enable(recording, "jdk.ObjectAllocationSample", true, null, null);
|
||||
}
|
||||
if (preset == Preset.FULL) {
|
||||
enable(recording, "jdk.ExecutionSample", true, Duration.ofMillis(20), null);
|
||||
enable(recording, "jdk.NativeMethodSample", true, Duration.ofMillis(20), null);
|
||||
enable(recording, "jdk.ThreadPark", true, null, Duration.ofMillis(1));
|
||||
enable(recording, "jdk.JavaMonitorEnter", true, null, Duration.ofMillis(1));
|
||||
}
|
||||
}
|
||||
|
||||
private static void enable(
|
||||
Recording recording,
|
||||
String eventName,
|
||||
boolean stackTrace,
|
||||
Duration period,
|
||||
Duration threshold
|
||||
) {
|
||||
try {
|
||||
EventSettings settings = recording.enable(eventName);
|
||||
settings = stackTrace ? settings.withStackTrace() : settings.withoutStackTrace();
|
||||
if (period != null) {
|
||||
settings = settings.withPeriod(period);
|
||||
}
|
||||
if (threshold != null) {
|
||||
settings = settings.withThreshold(threshold);
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// Some runtimes ship a slightly different event set.
|
||||
}
|
||||
}
|
||||
|
||||
private static Path ensureOutputDirectory() throws Exception {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
Path dir;
|
||||
if (mc != null && mc.gameDirectory != null) {
|
||||
dir = mc.gameDirectory.toPath().resolve("profile").resolve("jfr");
|
||||
} else {
|
||||
dir = Path.of("profile", "jfr");
|
||||
}
|
||||
Files.createDirectories(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static String defaultFileName(Preset preset, boolean snapshot) {
|
||||
String timestamp = FILE_TIME.format(LocalDateTime.now(ZoneId.systemDefault()));
|
||||
String suffix = snapshot ? "-snapshot" : "";
|
||||
return "lovisual-" + preset.getId() + suffix + "-" + timestamp + ".jfr";
|
||||
}
|
||||
|
||||
private static String formatDuration(long totalSeconds) {
|
||||
long minutes = totalSeconds / 60L;
|
||||
long seconds = totalSeconds % 60L;
|
||||
if (minutes <= 0L) {
|
||||
return seconds + "s";
|
||||
}
|
||||
return minutes + "m " + seconds + "s";
|
||||
}
|
||||
|
||||
public enum Preset {
|
||||
GC("gc"),
|
||||
ALLOC("alloc"),
|
||||
FULL("full");
|
||||
|
||||
private final String id;
|
||||
|
||||
Preset(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public static Preset parse(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return FULL;
|
||||
}
|
||||
return switch (raw.toLowerCase()) {
|
||||
case "gc" -> GC;
|
||||
case "alloc", "allocation", "allocs" -> ALLOC;
|
||||
case "full", "all", "profile" -> FULL;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
public String id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public boolean capturesAllocations() {
|
||||
return this == ALLOC || this == FULL;
|
||||
}
|
||||
}
|
||||
|
||||
public record StartResult(boolean started, boolean alreadyRunning, Preset preset, Path path, Instant startedAt,
|
||||
String error) {
|
||||
private static StartResult started(Preset preset, Path path, Instant startedAt) {
|
||||
return new StartResult(true, false, preset, path, startedAt, null);
|
||||
}
|
||||
|
||||
private static StartResult alreadyRunning(Preset preset, Path path, Instant startedAt) {
|
||||
return new StartResult(false, true, preset, path, startedAt, null);
|
||||
}
|
||||
|
||||
private static StartResult failed(String error) {
|
||||
return new StartResult(false, false, null, null, null, error);
|
||||
}
|
||||
}
|
||||
|
||||
public record DumpResult(boolean dumped, boolean notRunning, Path path, String error) {
|
||||
private static DumpResult dumped(Path path) {
|
||||
return new DumpResult(true, false, path, null);
|
||||
}
|
||||
|
||||
private static DumpResult notRunningResult() {
|
||||
return new DumpResult(false, true, null, null);
|
||||
}
|
||||
|
||||
private static DumpResult failed(String error) {
|
||||
return new DumpResult(false, false, null, error);
|
||||
}
|
||||
}
|
||||
|
||||
public record StopResult(boolean stopped, boolean notRunning, Preset preset, Path path, Instant startedAt,
|
||||
String error) {
|
||||
private static StopResult stopped(Preset preset, Path path, Instant startedAt) {
|
||||
return new StopResult(true, false, preset, path, startedAt, null);
|
||||
}
|
||||
|
||||
private static StopResult notRunningResult() {
|
||||
return new StopResult(false, true, null, null, null, null);
|
||||
}
|
||||
|
||||
private static StopResult failed(String error) {
|
||||
return new StopResult(false, false, null, null, null, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
|
||||
public enum DevProfilerPhase {
|
||||
;
|
||||
|
||||
private static final ThreadLocal<ArrayDeque<String>> STACK =
|
||||
ThreadLocal.withInitial(ArrayDeque::new);
|
||||
|
||||
public static Scope scope(String label) {
|
||||
if (label == null || label.isBlank()) return Scope.NOOP;
|
||||
begin(label);
|
||||
return new Scope(true);
|
||||
}
|
||||
|
||||
public static void begin(String label) {
|
||||
if (label == null || label.isBlank()) return;
|
||||
if (!DevSamplingProfiler.isActive()) return;
|
||||
STACK.get().push(label);
|
||||
}
|
||||
|
||||
public static void end(String label) {
|
||||
if (label == null || label.isBlank()) return;
|
||||
ArrayDeque<String> stack = STACK.get();
|
||||
if (stack == null || stack.isEmpty()) return;
|
||||
String top = stack.peek();
|
||||
if (label.equals(top)) {
|
||||
pop();
|
||||
}
|
||||
}
|
||||
|
||||
public static String current() {
|
||||
ArrayDeque<String> stack = STACK.get();
|
||||
if (stack == null || stack.isEmpty()) return "unknown";
|
||||
String v = stack.peek();
|
||||
return v == null || v.isBlank() ? "unknown" : v;
|
||||
}
|
||||
|
||||
public static void clearCurrent() {
|
||||
ArrayDeque<String> stack = STACK.get();
|
||||
if (stack != null) {
|
||||
stack.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private static void pop() {
|
||||
ArrayDeque<String> stack = STACK.get();
|
||||
if (stack == null || stack.isEmpty()) return;
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
public static final class Scope implements AutoCloseable {
|
||||
private static final Scope NOOP = new Scope(false);
|
||||
private final boolean active;
|
||||
|
||||
private Scope(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!active) return;
|
||||
pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,457 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Low-overhead owner/effect profiler for the new RHI path.
|
||||
*
|
||||
* <p>The existing DevRenderProfiler2D/3D tree answers "which Java section is hot".
|
||||
* This profiler answers the practical render question: which phase/widget/node/effect/pass
|
||||
* consumed CPU time and caused RHI work (draws, uploads, fullscreen passes, copies, uniforms).</p>
|
||||
*/
|
||||
public enum DevRenderCostProfiler {
|
||||
;
|
||||
private static final int MAX_BUCKETS = 768;
|
||||
private static final long NS_IN_MS = 1_000_000L;
|
||||
private static final int DEFAULT_LOG_INTERVAL_FRAMES = 120;
|
||||
private static final int DEFAULT_LOG_TOP = 20;
|
||||
private static final double DEFAULT_LOG_MIN_MS = 0.02;
|
||||
|
||||
private static final String PROP_ENABLED = "lovisual.profiler.renderCost";
|
||||
private static final String PROP_LOG = "lovisual.profiler.renderCost.log";
|
||||
private static final String PROP_INTERVAL = "lovisual.profiler.renderCost.interval";
|
||||
private static final String PROP_TOP = "lovisual.profiler.renderCost.top";
|
||||
private static final String PROP_MIN_MS = "lovisual.profiler.renderCost.minMs";
|
||||
|
||||
private static final LinkedHashMap<String, Bucket> buckets = new LinkedHashMap<>();
|
||||
private static final HashMap<String, String> labelCache = new HashMap<>(256);
|
||||
private static final ThreadLocal<Deque<Scope>> scopeStack = ThreadLocal.withInitial(ArrayDeque::new);
|
||||
private static long frameId = Long.MIN_VALUE;
|
||||
private static long lastLoggedFrameId = Long.MIN_VALUE;
|
||||
private static boolean active;
|
||||
private static Snapshot snapshot = Snapshot.EMPTY;
|
||||
|
||||
public static void beginFrame(long newFrameId) {
|
||||
if (frameId == newFrameId) return;
|
||||
frameId = newFrameId;
|
||||
active = isProfilerEnabled();
|
||||
if (!active) {
|
||||
snapshot = Snapshot.EMPTY;
|
||||
return;
|
||||
}
|
||||
buckets.clear();
|
||||
scopeStack.get().clear();
|
||||
}
|
||||
|
||||
public static void endFrame() {
|
||||
if (!active) return;
|
||||
snapshot = Snapshot.from(frameId, buckets);
|
||||
emitLogIfDue(snapshot);
|
||||
active = false;
|
||||
}
|
||||
|
||||
public static Snapshot snapshot() {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public static boolean isConfigured() {
|
||||
return Boolean.getBoolean(PROP_ENABLED);
|
||||
}
|
||||
|
||||
public static Scope scope(String domain, String name) {
|
||||
if (!active) return Scope.NOOP;
|
||||
String d = clean(domain, "unknown");
|
||||
String n = clean(name, "unnamed");
|
||||
String owner = clean(DevProfilerPhase.current(), "unknown");
|
||||
Bucket bucket = bucket(d, owner, n);
|
||||
if (bucket == null) return Scope.NOOP;
|
||||
Scope scope = new Scope(bucket, System.nanoTime(), Counters.capture(), true);
|
||||
scopeStack.get().push(scope);
|
||||
return scope;
|
||||
}
|
||||
|
||||
public static Scope phase(String label) {
|
||||
return scope("phase", label);
|
||||
}
|
||||
|
||||
public static Scope uiNode(Object label) {
|
||||
return scope("ui.node", String.valueOf(label));
|
||||
}
|
||||
|
||||
public static Scope uiRuntime(String label) {
|
||||
return scope("ui.runtime", label);
|
||||
}
|
||||
|
||||
public static Scope uiEffect(String label) {
|
||||
return scope("ui.effect", label);
|
||||
}
|
||||
|
||||
public static Scope postPass(String label) {
|
||||
return scope("post.pass", label);
|
||||
}
|
||||
|
||||
public static Scope rhiDraw(String label) {
|
||||
return scope("rhi.draw", label);
|
||||
}
|
||||
|
||||
public static Scope itemRender(String label) {
|
||||
return scope("item.render", label);
|
||||
}
|
||||
|
||||
public static Scope worldEffect(String label) {
|
||||
return scope("world.effect", label);
|
||||
}
|
||||
|
||||
public static List<String> debugLines(String title, String domainPrefix, int limit, double minMs) {
|
||||
Snapshot snap = snapshot;
|
||||
if (snap == null || snap.entries.isEmpty()) return List.of();
|
||||
String prefix = domainPrefix == null ? "" : domainPrefix;
|
||||
List<Entry> filtered = new ArrayList<>();
|
||||
for (Entry entry : snap.entries) {
|
||||
if (prefix.isEmpty() || entry.domain.startsWith(prefix)) {
|
||||
filtered.add(entry);
|
||||
}
|
||||
}
|
||||
if (filtered.isEmpty()) return List.of();
|
||||
|
||||
filtered.sort(Comparator
|
||||
.comparingLong((Entry e) -> e.totalNs).reversed()
|
||||
.thenComparingLong((Entry e) -> e.uploadedBytes).reversed()
|
||||
.thenComparingLong((Entry e) -> e.drawCalls).reversed());
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.add(title + ":");
|
||||
int count = 0;
|
||||
for (Entry e : filtered) {
|
||||
double ms = e.totalNs / (double) NS_IN_MS;
|
||||
if (ms < minMs) continue;
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
" %d) [%s] %s:%s %.2f ms max %.2f calls %d | draw %d upload %d/%s fs %d copy %d/%d uni %d/%s",
|
||||
count + 1,
|
||||
shorten(e.owner, 42),
|
||||
e.domain,
|
||||
shorten(e.name, 56),
|
||||
ms,
|
||||
e.maxNs / (double) NS_IN_MS,
|
||||
e.calls,
|
||||
e.drawCalls,
|
||||
e.meshUploads,
|
||||
formatBytes(e.uploadedBytes),
|
||||
e.fullscreenPasses,
|
||||
e.fastCopies,
|
||||
e.shaderCopies,
|
||||
e.uniformWrites,
|
||||
formatBytes(e.uniformBytes)));
|
||||
count++;
|
||||
if (count >= limit) break;
|
||||
}
|
||||
if (count == 0) return List.of();
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static boolean isProfilerEnabled() {
|
||||
return Boolean.getBoolean(PROP_ENABLED);
|
||||
}
|
||||
|
||||
private static boolean shouldLogToLatest() {
|
||||
if (!Boolean.getBoolean(PROP_ENABLED)) return false;
|
||||
return Boolean.parseBoolean(System.getProperty(PROP_LOG, "true"));
|
||||
}
|
||||
|
||||
private static void emitLogIfDue(Snapshot snap) {
|
||||
if (!shouldLogToLatest()) return;
|
||||
if (snap == null || snap.entries.isEmpty()) return;
|
||||
|
||||
int interval = intProperty(PROP_INTERVAL, DEFAULT_LOG_INTERVAL_FRAMES, 1, 60_000);
|
||||
if (lastLoggedFrameId != Long.MIN_VALUE && snap.frameId - lastLoggedFrameId < interval) return;
|
||||
lastLoggedFrameId = snap.frameId;
|
||||
|
||||
int top = intProperty(PROP_TOP, DEFAULT_LOG_TOP, 1, 200);
|
||||
double minMs = doubleProperty(PROP_MIN_MS, DEFAULT_LOG_MIN_MS, 0.0, 1_000.0);
|
||||
|
||||
ProfilerLog.info("[RenderCost] frame=%d buckets=%d interval=%d top=%d minMs=%.3f", snap.frameId, snap.entries.size(), interval, top, minMs);
|
||||
emitDomainToLog("phases", "phase", top, minMs);
|
||||
emitDomainToLog("ui runtime", "ui.runtime", top, minMs);
|
||||
emitDomainToLog("ui nodes", "ui.node", top, minMs);
|
||||
emitDomainToLog("ui effects", "ui.effect", top, minMs);
|
||||
emitDomainToLog("item render", "item.render", top, minMs);
|
||||
emitDomainToLog("world effects", "world.effect", top, minMs);
|
||||
emitDomainToLog("post passes", "post.pass", top, minMs);
|
||||
emitDomainToLog("rhi draws", "rhi.draw", top, minMs);
|
||||
}
|
||||
|
||||
private static void emitDomainToLog(String title, String prefix, int top, double minMs) {
|
||||
List<String> lines = debugLines("[RenderCost] " + title, prefix, top, minMs);
|
||||
for (String line : lines) {
|
||||
ProfilerLog.info("%s", line);
|
||||
}
|
||||
}
|
||||
|
||||
private static int intProperty(String key, int fallback, int min, int max) {
|
||||
String raw = System.getProperty(key);
|
||||
if (raw == null || raw.isBlank()) return fallback;
|
||||
try {
|
||||
int value = Integer.parseInt(raw.trim());
|
||||
return Math.max(min, Math.min(max, value));
|
||||
} catch (NumberFormatException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private static double doubleProperty(String key, double fallback, double min, double max) {
|
||||
String raw = System.getProperty(key);
|
||||
if (raw == null || raw.isBlank()) return fallback;
|
||||
try {
|
||||
double value = Double.parseDouble(raw.trim());
|
||||
if (!Double.isFinite(value)) return fallback;
|
||||
return Math.max(min, Math.min(max, value));
|
||||
} catch (NumberFormatException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private static Bucket bucket(String domain, String owner, String name) {
|
||||
String key = domain + '\u001F' + owner + '\u001F' + name;
|
||||
Bucket existing = buckets.get(key);
|
||||
if (existing != null) return existing;
|
||||
if (buckets.size() >= MAX_BUCKETS) {
|
||||
key = "overflow\u001F" + owner + "\u001Fother";
|
||||
existing = buckets.get(key);
|
||||
if (existing != null) return existing;
|
||||
if (buckets.size() >= MAX_BUCKETS + 1) return null;
|
||||
Bucket overflow = new Bucket("overflow", owner, "other");
|
||||
buckets.put(key, overflow);
|
||||
return overflow;
|
||||
}
|
||||
Bucket created = new Bucket(domain, owner, name);
|
||||
buckets.put(key, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
private static String clean(String raw, String fallback) {
|
||||
if (raw == null || raw.isBlank()) return fallback;
|
||||
String s = raw.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ').trim();
|
||||
return s.isEmpty() ? fallback : s;
|
||||
}
|
||||
|
||||
private static String shorten(String s, int max) {
|
||||
if (s == null) return "";
|
||||
if (s.length() <= max) return s;
|
||||
if (max <= 3) return s.substring(0, max);
|
||||
return s.substring(0, max - 3) + "...";
|
||||
}
|
||||
|
||||
private static String formatBytes(long bytes) {
|
||||
if (bytes < 1024L) return bytes + " B";
|
||||
double kb = bytes / 1024.0;
|
||||
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
|
||||
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
|
||||
}
|
||||
|
||||
public static final class Scope implements AutoCloseable {
|
||||
private static final Scope NOOP = new Scope(null, 0L, Counters.ZERO, false);
|
||||
private final Bucket bucket;
|
||||
private final long startNs;
|
||||
private final Counters begin;
|
||||
private final boolean enabled;
|
||||
private boolean closed;
|
||||
private long childNs;
|
||||
private Counters childCounters = Counters.ZERO;
|
||||
|
||||
private Scope(Bucket bucket, long startNs, Counters begin, boolean enabled) {
|
||||
this.bucket = bucket;
|
||||
this.startNs = startNs;
|
||||
this.begin = begin;
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!enabled || closed || bucket == null) return;
|
||||
closed = true;
|
||||
long elapsed = Math.max(0L, System.nanoTime() - startNs);
|
||||
Counters rawDelta = begin.deltaTo(Counters.capture());
|
||||
|
||||
Deque<Scope> stack = scopeStack.get();
|
||||
if (!stack.isEmpty() && stack.peek() == this) {
|
||||
stack.pop();
|
||||
} else {
|
||||
stack.remove(this);
|
||||
}
|
||||
|
||||
if (!stack.isEmpty()) {
|
||||
Scope parent = stack.peek();
|
||||
parent.childNs += elapsed;
|
||||
parent.childCounters = parent.childCounters.plus(rawDelta);
|
||||
}
|
||||
|
||||
long bucketNs = elapsed;
|
||||
Counters bucketCounters = rawDelta;
|
||||
if ("ui.node".equals(bucket.domain)) {
|
||||
bucketNs = Math.max(0L, elapsed - childNs);
|
||||
bucketCounters = rawDelta.minus(childCounters);
|
||||
}
|
||||
bucket.add(bucketNs, bucketCounters);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Bucket {
|
||||
final String domain;
|
||||
final String owner;
|
||||
final String name;
|
||||
long calls;
|
||||
long totalNs;
|
||||
long maxNs;
|
||||
long drawCalls;
|
||||
long meshUploads;
|
||||
long fullscreenPasses;
|
||||
long fastCopies;
|
||||
long shaderCopies;
|
||||
long uploadedBytes;
|
||||
long uniformWrites;
|
||||
long uniformBytes;
|
||||
|
||||
private Bucket(String domain, String owner, String name) {
|
||||
this.domain = domain;
|
||||
this.owner = owner;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
void add(long ns, Counters d) {
|
||||
calls++;
|
||||
totalNs += ns;
|
||||
maxNs = Math.max(maxNs, ns);
|
||||
if (d == null) return;
|
||||
drawCalls += d.drawCalls;
|
||||
meshUploads += d.meshUploads;
|
||||
fullscreenPasses += d.fullscreenPasses;
|
||||
fastCopies += d.fastCopies;
|
||||
shaderCopies += d.shaderCopies;
|
||||
uploadedBytes += d.uploadedBytes;
|
||||
uniformWrites += d.uniformWrites;
|
||||
uniformBytes += d.uniformBytes;
|
||||
}
|
||||
}
|
||||
|
||||
private record Counters(long drawCalls,
|
||||
long meshUploads,
|
||||
long fullscreenPasses,
|
||||
long fastCopies,
|
||||
long shaderCopies,
|
||||
long uploadedBytes,
|
||||
long uniformWrites,
|
||||
long uniformBytes) {
|
||||
static final Counters ZERO = new Counters(0, 0, 0, 0, 0, 0, 0, 0);
|
||||
|
||||
static Counters capture() {
|
||||
try {
|
||||
long uploaded = LoVisualRenderSystem.rhi().stats().uploadedVertexBytes()
|
||||
+ LoVisualRenderSystem.rhi().stats().uploadedIndexBytes();
|
||||
return new Counters(
|
||||
LoVisualRenderSystem.rhi().stats().drawCalls(),
|
||||
LoVisualRenderSystem.rhi().stats().meshUploads(),
|
||||
LoVisualRenderSystem.rhi().stats().fullscreenPasses(),
|
||||
LoVisualRenderSystem.rhi().stats().textureFastCopies(),
|
||||
LoVisualRenderSystem.rhi().stats().textureShaderCopies(),
|
||||
uploaded,
|
||||
LoVisualRenderSystem.uniforms().stats().writes(),
|
||||
LoVisualRenderSystem.uniforms().stats().uploadedBytes()
|
||||
);
|
||||
} catch (Throwable ignored) {
|
||||
return ZERO;
|
||||
}
|
||||
}
|
||||
|
||||
Counters deltaTo(Counters end) {
|
||||
if (end == null) return ZERO;
|
||||
return new Counters(
|
||||
Math.max(0L, end.drawCalls - drawCalls),
|
||||
Math.max(0L, end.meshUploads - meshUploads),
|
||||
Math.max(0L, end.fullscreenPasses - fullscreenPasses),
|
||||
Math.max(0L, end.fastCopies - fastCopies),
|
||||
Math.max(0L, end.shaderCopies - shaderCopies),
|
||||
Math.max(0L, end.uploadedBytes - uploadedBytes),
|
||||
Math.max(0L, end.uniformWrites - uniformWrites),
|
||||
Math.max(0L, end.uniformBytes - uniformBytes)
|
||||
);
|
||||
}
|
||||
|
||||
Counters plus(Counters other) {
|
||||
if (other == null) return this;
|
||||
return new Counters(
|
||||
drawCalls + other.drawCalls,
|
||||
meshUploads + other.meshUploads,
|
||||
fullscreenPasses + other.fullscreenPasses,
|
||||
fastCopies + other.fastCopies,
|
||||
shaderCopies + other.shaderCopies,
|
||||
uploadedBytes + other.uploadedBytes,
|
||||
uniformWrites + other.uniformWrites,
|
||||
uniformBytes + other.uniformBytes
|
||||
);
|
||||
}
|
||||
|
||||
Counters minus(Counters other) {
|
||||
if (other == null) return this;
|
||||
return new Counters(
|
||||
Math.max(0L, drawCalls - other.drawCalls),
|
||||
Math.max(0L, meshUploads - other.meshUploads),
|
||||
Math.max(0L, fullscreenPasses - other.fullscreenPasses),
|
||||
Math.max(0L, fastCopies - other.fastCopies),
|
||||
Math.max(0L, shaderCopies - other.shaderCopies),
|
||||
Math.max(0L, uploadedBytes - other.uploadedBytes),
|
||||
Math.max(0L, uniformWrites - other.uniformWrites),
|
||||
Math.max(0L, uniformBytes - other.uniformBytes)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public record Snapshot(long frameId, List<Entry> entries) {
|
||||
static final Snapshot EMPTY = new Snapshot(Long.MIN_VALUE, List.of());
|
||||
|
||||
static Snapshot from(long frameId, Map<String, Bucket> buckets) {
|
||||
if (buckets == null || buckets.isEmpty()) return EMPTY;
|
||||
List<Entry> out = new ArrayList<>(buckets.size());
|
||||
for (Bucket b : buckets.values()) {
|
||||
out.add(new Entry(
|
||||
b.domain,
|
||||
b.owner,
|
||||
b.name,
|
||||
b.calls,
|
||||
b.totalNs,
|
||||
b.maxNs,
|
||||
b.drawCalls,
|
||||
b.meshUploads,
|
||||
b.fullscreenPasses,
|
||||
b.fastCopies,
|
||||
b.shaderCopies,
|
||||
b.uploadedBytes,
|
||||
b.uniformWrites,
|
||||
b.uniformBytes
|
||||
));
|
||||
}
|
||||
return new Snapshot(frameId, List.copyOf(out));
|
||||
}
|
||||
}
|
||||
|
||||
public record Entry(String domain,
|
||||
String owner,
|
||||
String name,
|
||||
long calls,
|
||||
long totalNs,
|
||||
long maxNs,
|
||||
long drawCalls,
|
||||
long meshUploads,
|
||||
long fullscreenPasses,
|
||||
long fastCopies,
|
||||
long shaderCopies,
|
||||
long uploadedBytes,
|
||||
long uniformWrites,
|
||||
long uniformBytes) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,135 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import dev.loki.lovisual.render.engine.core.RenderPhase;
|
||||
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
|
||||
|
||||
/**
|
||||
* Single profiler bridge for the RHI/FrameGraph lifecycle.
|
||||
* Existing DevRenderProfiler2D/3D trees are preserved, but phase ownership moves here.
|
||||
*/
|
||||
public enum DevRenderFrameProfiler {
|
||||
;
|
||||
private static boolean worldFrameOpen;
|
||||
private static boolean uiFrameOpen;
|
||||
|
||||
public static void beginFrame(long frameId) {
|
||||
// The sampling profiler is still driven by 2D/3D beginFrame calls below.
|
||||
DevRenderCostProfiler.beginFrame(frameId);
|
||||
}
|
||||
|
||||
public static PhaseScope phase(RenderPhase phase, String label) {
|
||||
RenderPhase actualPhase = phase == null ? RenderPhase.NONE : phase;
|
||||
String actualLabel = label == null || label.isBlank() ? defaultLabel(actualPhase) : label;
|
||||
|
||||
DevProfilerPhase.Scope cpu = DevProfilerPhase.scope(actualLabel);
|
||||
DevRenderCostProfiler.Scope cost = DevRenderCostProfiler.phase(actualLabel);
|
||||
DevTracyGpuProfiler.Scope gpu = DevTracyGpuProfiler.beginZone(actualLabel);
|
||||
AutoCloseable tree = beginTreeSection(actualPhase, actualLabel);
|
||||
return new PhaseScope(cpu, cost, gpu, tree);
|
||||
}
|
||||
|
||||
public static void endFrame(RhiStatsSnapshot rhi, UniformAllocatorStatsSnapshot uniforms) {
|
||||
DevRenderCostProfiler.endFrame();
|
||||
if (worldFrameOpen) {
|
||||
DevRenderProfiler3D.endFrame();
|
||||
worldFrameOpen = false;
|
||||
}
|
||||
if (uiFrameOpen) {
|
||||
DevRenderProfiler2D.endFrame();
|
||||
uiFrameOpen = false;
|
||||
}
|
||||
DevGlSyncTracker.emitTracyFrame();
|
||||
DevTracyProfiler.markFrame();
|
||||
}
|
||||
|
||||
private static AutoCloseable beginTreeSection(RenderPhase phase, String label) {
|
||||
if (isWorld(phase)) {
|
||||
if (!worldFrameOpen) {
|
||||
DevRenderProfiler3D.beginFrame("world");
|
||||
worldFrameOpen = true;
|
||||
}
|
||||
return DevRenderProfiler3D.section(stripDomain(label));
|
||||
}
|
||||
if (isUi(phase)) {
|
||||
if (!uiFrameOpen) {
|
||||
DevRenderProfiler2D.beginFrame("ui");
|
||||
uiFrameOpen = true;
|
||||
}
|
||||
return DevRenderProfiler2D.section(stripDomain(label));
|
||||
}
|
||||
return () -> {
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean isWorld(RenderPhase phase) {
|
||||
return phase == RenderPhase.WORLD_BEFORE_ENTITIES
|
||||
|| phase == RenderPhase.WORLD_AFTER_ENTITIES
|
||||
|| phase == RenderPhase.WORLD_BEFORE_TRANSLUCENT
|
||||
|| phase == RenderPhase.WORLD_AFTER_TRANSLUCENT
|
||||
|| phase == RenderPhase.WORLD_POST_PRE_HAND
|
||||
|| phase == RenderPhase.WORLD_POST_HAND;
|
||||
}
|
||||
|
||||
private static boolean isUi(RenderPhase phase) {
|
||||
return phase == RenderPhase.HUD_CAPTURE
|
||||
|| phase == RenderPhase.HUD_MAIN
|
||||
|| phase == RenderPhase.HUD_EFFECTS
|
||||
|| phase == RenderPhase.SCREEN_TOP
|
||||
|| phase == RenderPhase.SCREEN;
|
||||
}
|
||||
|
||||
private static String defaultLabel(RenderPhase phase) {
|
||||
return switch (phase) {
|
||||
case WORLD_BEFORE_ENTITIES -> "3d:world_before_entities";
|
||||
case WORLD_AFTER_ENTITIES -> "3d:world_after_entities";
|
||||
case WORLD_BEFORE_TRANSLUCENT -> "3d:world_before_translucent";
|
||||
case WORLD_AFTER_TRANSLUCENT -> "3d:world_after_translucent";
|
||||
case WORLD_POST_PRE_HAND -> "3d:post_pre_hand";
|
||||
case WORLD_POST_HAND -> "3d:post_hand";
|
||||
case HUD_CAPTURE -> "2d:hud_capture";
|
||||
case HUD_MAIN -> "2d:hud_main";
|
||||
case HUD_EFFECTS -> "2d:hud_effects";
|
||||
case SCREEN_TOP -> "2d:screen_top";
|
||||
case SCREEN -> "2d:screen";
|
||||
case LEGACY_SHADOW_TERRAIN -> "3d:shadow_terrain_legacy";
|
||||
default -> "render:none";
|
||||
};
|
||||
}
|
||||
|
||||
private static String stripDomain(String label) {
|
||||
int idx = label.indexOf(':');
|
||||
if (idx >= 0 && idx + 1 < label.length()) {
|
||||
return label.substring(idx + 1);
|
||||
}
|
||||
return label;
|
||||
}
|
||||
|
||||
public static final class PhaseScope implements AutoCloseable {
|
||||
private final DevProfilerPhase.Scope cpu;
|
||||
private final DevRenderCostProfiler.Scope cost;
|
||||
private final DevTracyGpuProfiler.Scope gpu;
|
||||
private final AutoCloseable tree;
|
||||
private boolean closed;
|
||||
|
||||
private PhaseScope(DevProfilerPhase.Scope cpu, DevRenderCostProfiler.Scope cost, DevTracyGpuProfiler.Scope gpu, AutoCloseable tree) {
|
||||
this.cpu = cpu;
|
||||
this.cost = cost;
|
||||
this.gpu = gpu;
|
||||
this.tree = tree;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
try {
|
||||
if (tree != null) tree.close();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
if (gpu != null) gpu.close();
|
||||
if (cost != null) cost.close();
|
||||
if (cpu != null) cpu.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,498 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import dev.loki.lovisual.render.engine.command.UiStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.ui.runtime.script.CachedUiScriptRuntime;
|
||||
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.text.TextCommandStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.text.TextRenderSystem;
|
||||
import dev.loki.lovisual.render.engine.uniform.MeshBuilder;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public enum DevRenderProfiler2D {
|
||||
;
|
||||
|
||||
private static final long NS_IN_MS = 1_000_000L;
|
||||
private static final int DEFAULT_TOP_LIMIT = 6;
|
||||
private static final int DEFAULT_TREE_DEPTH = 32;
|
||||
private static final double DEFAULT_MIN_MS = 0.0;
|
||||
private static final long DEFAULT_EMIT_INTERVAL_NS = 1_000_000_000L;
|
||||
private static final ArrayDeque<Node> stack = new ArrayDeque<>();
|
||||
private static boolean active;
|
||||
private static Node root;
|
||||
private static Node snapshot;
|
||||
private static long lastEmitNs;
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
|
||||
}
|
||||
|
||||
public static void beginFrame(String name) {
|
||||
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.UI);
|
||||
if (!isEnabled()) return;
|
||||
CachedUiScriptRuntime.resetFrameStats();
|
||||
MeshBuilder.resetFrameStats();
|
||||
active = true;
|
||||
root = new Node(name, null);
|
||||
stack.clear();
|
||||
stack.push(root);
|
||||
root.startNs = System.nanoTime();
|
||||
}
|
||||
|
||||
public static boolean beginFrameIfNeeded(String name) {
|
||||
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.UI);
|
||||
if (!isEnabled() || active) return false;
|
||||
beginFrame(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void endFrame() {
|
||||
if (!isEnabled() || !active) return;
|
||||
long now = System.nanoTime();
|
||||
while (stack.size() > 1) {
|
||||
endSection();
|
||||
}
|
||||
Node r = stack.peek();
|
||||
if (r != null) {
|
||||
r.calls = Math.max(1, r.calls);
|
||||
r.totalNs += now - r.startNs;
|
||||
r.startNs = 0L;
|
||||
snapshot = r;
|
||||
DevTracyProfiler.plotUiFrame(r.totalNs / (double) NS_IN_MS, r.countNodes());
|
||||
}
|
||||
active = false;
|
||||
emitIfDue(now);
|
||||
}
|
||||
|
||||
public static Section section(String name) {
|
||||
if (!isEnabled() || !active) return Section.NOOP;
|
||||
beginSection(name);
|
||||
return new Section(true);
|
||||
}
|
||||
|
||||
private static void beginSection(String name) {
|
||||
Node parent = stack.peek();
|
||||
if (parent == null) return;
|
||||
Node child = parent.children.computeIfAbsent(name, n -> new Node(n, parent));
|
||||
child.calls += 1;
|
||||
child.startNs = System.nanoTime();
|
||||
stack.push(child);
|
||||
}
|
||||
|
||||
private static void endSection() {
|
||||
Node node = stack.poll();
|
||||
if (node == null) return;
|
||||
long now = System.nanoTime();
|
||||
node.totalNs += now - node.startNs;
|
||||
node.startNs = 0L;
|
||||
}
|
||||
|
||||
public static List<String> getDebugLines() {
|
||||
return getDebugLines(DEFAULT_TOP_LIMIT, DEFAULT_TREE_DEPTH, DEFAULT_MIN_MS);
|
||||
}
|
||||
|
||||
public static List<String> getDebugLines(int topLimit, int depthLimit, double minMs) {
|
||||
if (!isEnabled()) return List.of();
|
||||
Node snap = snapshot;
|
||||
if (snap == null) return List.of();
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
double totalMs = snap.totalNs / (double) NS_IN_MS;
|
||||
lines.add(String.format("ui prof: %.2f ms, nodes %d", totalMs, snap.countNodes()));
|
||||
appendRuntimeCounters(lines);
|
||||
|
||||
List<Node> flat = new ArrayList<>();
|
||||
collectFlat(snap, flat);
|
||||
flat.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
|
||||
|
||||
int top = Math.min(topLimit, flat.size());
|
||||
if (top > 0) {
|
||||
lines.add("ui prof top:");
|
||||
for (int i = 0; i < top; i++) {
|
||||
Node n = flat.get(i);
|
||||
double ms = n.totalNs / (double) NS_IN_MS;
|
||||
if (ms < minMs) break;
|
||||
double selfMs = selfNs(n) / (double) NS_IN_MS;
|
||||
Node hot = hottestChild(n);
|
||||
if (hot != null) {
|
||||
double hotMs = hot.totalNs / (double) NS_IN_MS;
|
||||
lines.add(String.format(
|
||||
" %d) %s %.2f ms (self %.2f, hot %s %.2f, %d)",
|
||||
i + 1,
|
||||
nodePath(n),
|
||||
ms,
|
||||
selfMs,
|
||||
hot.name,
|
||||
hotMs,
|
||||
n.calls
|
||||
));
|
||||
} else {
|
||||
lines.add(String.format(
|
||||
" %d) %s %.2f ms (self %.2f, %d)",
|
||||
i + 1,
|
||||
nodePath(n),
|
||||
ms,
|
||||
selfMs,
|
||||
n.calls
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.add("ui prof tree:");
|
||||
appendTreeAscii(lines, snap, "", 0, depthLimit, minMs);
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static void appendRuntimeCounters(List<String> lines) {
|
||||
CachedUiScriptRuntime.FrameStatsSnapshot ui = CachedUiScriptRuntime.frameStatsSnapshot();
|
||||
if (ui.bakeCalls() > 0 || ui.jsRenders() > 0 || ui.layoutPasses() > 0 || ui.propPatches() > 0 || ui.boundsPatches() > 0) {
|
||||
lines.add(String.format(
|
||||
"ui runtime: bake %d, js %d, layout %d, propPatch %d/%d, boundsPatch %d/%d, blocked %d, fail %d",
|
||||
ui.bakeCalls(),
|
||||
ui.jsRenders(),
|
||||
ui.layoutPasses(),
|
||||
ui.propPatchPasses(),
|
||||
ui.propPatches(),
|
||||
ui.boundsPatchPasses(),
|
||||
ui.boundsPatches(),
|
||||
ui.blockedCalls(),
|
||||
ui.failedRenders()
|
||||
));
|
||||
}
|
||||
|
||||
TextCommandStatsSnapshot textStats = LoVisualRenderSystem.textStatsSnapshot();
|
||||
if (textStats.recorded() > 0 || textStats.meshUploads() > 0 || textStats.glyphs() > 0) {
|
||||
lines.add(String.format(
|
||||
"text: rec/sub %d/%d, backend vanilla/bitmap/msdf/world %d/%d/%d/%d, effect/clip %d/%d, glyphs %d, meshUploads %d, router hit/miss/fallback %d/%d/%d, adjacent %d, uploaded v/i %s/%s",
|
||||
textStats.recorded(),
|
||||
textStats.submitted(),
|
||||
textStats.vanilla(),
|
||||
textStats.bitmap(),
|
||||
textStats.msdf(),
|
||||
textStats.world(),
|
||||
textStats.effect(),
|
||||
textStats.clipped(),
|
||||
textStats.glyphs(),
|
||||
textStats.meshUploads(),
|
||||
textStats.routerCacheHits(),
|
||||
textStats.routerCacheMisses(),
|
||||
textStats.routerFallbackMisses(),
|
||||
textStats.adjacentBatchedCommands(),
|
||||
formatBytes(textStats.uploadedVertexBytes()),
|
||||
formatBytes(textStats.uploadedIndexBytes())
|
||||
));
|
||||
}
|
||||
var glyphStats = TextRenderSystem.glyphAtlases().stats();
|
||||
if (glyphStats.pageCount() > 0 || glyphStats.dirtyUploads() > 0) {
|
||||
lines.add(String.format(
|
||||
"glyph atlas: pages %d, glyphs %d, dirtyUploads %d, uploaded %s",
|
||||
glyphStats.pageCount(),
|
||||
glyphStats.glyphCount(),
|
||||
glyphStats.dirtyUploads(),
|
||||
formatBytes(glyphStats.uploadedBytes())
|
||||
));
|
||||
}
|
||||
|
||||
UiStatsSnapshot uiDraw = Renderer2D.getUiStatsSnapshot();
|
||||
if (uiDraw.recordedCommands() > 0 || uiDraw.compiledBatches() > 0) {
|
||||
lines.add(String.format(
|
||||
"ui commands: total %d, shape/path/tex/text/item/effect %d/%d/%d/%d/%d/%d, compiled %d, backend %d",
|
||||
uiDraw.recordedCommands(),
|
||||
uiDraw.shapeCommands(),
|
||||
uiDraw.pathCommands(),
|
||||
uiDraw.textureCommands(),
|
||||
uiDraw.textCommands(),
|
||||
uiDraw.itemCommands(),
|
||||
uiDraw.effectCommands(),
|
||||
uiDraw.compiledBatches(),
|
||||
uiDraw.backendCommands()
|
||||
));
|
||||
}
|
||||
|
||||
Renderer2D.BatchStats batch = Renderer2D.getBatchStats();
|
||||
int frameBatches = batch.getFrameBatches();
|
||||
int frameDraws = batch.getFrameDraws();
|
||||
int frameVertices = batch.getFrameVertices();
|
||||
int frameIndices = batch.getFrameIndices();
|
||||
Map<Renderer2D.FlushReason, Integer> flushReasons = batch.getFrameFlushReasons();
|
||||
if (frameBatches > 0 || frameDraws > 0 || frameVertices > 0 || frameIndices > 0 || !flushReasons.isEmpty()) {
|
||||
lines.add(String.format(
|
||||
"ui batch: batches %d, draws %d, vertices %d, indices %d, pool %d, last %d/%d/%d, flush %s %s",
|
||||
frameBatches,
|
||||
frameDraws,
|
||||
frameVertices,
|
||||
frameIndices,
|
||||
batch.getPoolTotal(),
|
||||
batch.getLastOrder(),
|
||||
batch.getLastDraws(),
|
||||
batch.getLastVertices(),
|
||||
batch.getLastFlushReason(),
|
||||
formatFlushReasons(flushReasons)
|
||||
));
|
||||
}
|
||||
if (!batch.getLastError().isEmpty()) {
|
||||
lines.add("ui batch error: " + batch.getLastError());
|
||||
}
|
||||
|
||||
MeshBuilder.FrameStatsSnapshot mesh = MeshBuilder.frameStatsSnapshot();
|
||||
if (mesh.initialAllocations() > 0 || mesh.vertexReallocs() > 0 || mesh.indexReallocs() > 0) {
|
||||
lines.add(String.format(
|
||||
"ui mesh: alloc %d, realloc v/i %d/%d, bytes %s, max v/i %s/%s",
|
||||
mesh.initialAllocations(),
|
||||
mesh.vertexReallocs(),
|
||||
mesh.indexReallocs(),
|
||||
formatBytes(mesh.allocatedBytes()),
|
||||
formatBytes(mesh.maxVertexBytes()),
|
||||
formatBytes(mesh.maxIndexBytes())
|
||||
));
|
||||
}
|
||||
|
||||
appendRhiCounters(lines);
|
||||
var immediatelyFast = LoVisualRenderSystem.immediatelyFastSnapshot();
|
||||
if (immediatelyFast.modLoaded()) {
|
||||
lines.add(immediatelyFast.shortLine());
|
||||
}
|
||||
appendCostCounters(lines);
|
||||
}
|
||||
|
||||
private static String formatFlushReasons(Map<Renderer2D.FlushReason, Integer> reasons) {
|
||||
if (reasons == null || reasons.isEmpty()) return "{}";
|
||||
List<String> parts = new ArrayList<>();
|
||||
for (Map.Entry<Renderer2D.FlushReason, Integer> entry : reasons.entrySet()) {
|
||||
if (entry.getValue() != null && entry.getValue() > 0) {
|
||||
parts.add(entry.getKey().name().toLowerCase(Locale.ROOT) + "=" + entry.getValue());
|
||||
}
|
||||
}
|
||||
return parts.isEmpty() ? "{}" : "{" + String.join(",", parts) + "}";
|
||||
}
|
||||
|
||||
private static void appendCostCounters(List<String> lines) {
|
||||
List<String> phase = DevRenderCostProfiler.debugLines("render cost phases", "phase", 6, 0.02);
|
||||
if (!phase.isEmpty()) lines.addAll(phase);
|
||||
List<String> runtime = DevRenderCostProfiler.debugLines("ui cost runtime", "ui.runtime", 8, 0.02);
|
||||
if (!runtime.isEmpty()) lines.addAll(runtime);
|
||||
List<String> nodes = DevRenderCostProfiler.debugLines("ui cost nodes", "ui.node", 10, 0.02);
|
||||
if (!nodes.isEmpty()) lines.addAll(nodes);
|
||||
List<String> effects = DevRenderCostProfiler.debugLines("ui cost effects", "ui.effect", 8, 0.02);
|
||||
if (!effects.isEmpty()) lines.addAll(effects);
|
||||
List<String> items = DevRenderCostProfiler.debugLines("ui cost item render", "item.render", 8, 0.02);
|
||||
if (!items.isEmpty()) lines.addAll(items);
|
||||
List<String> rhi = DevRenderCostProfiler.debugLines("ui cost rhi draws", "rhi.draw", 8, 0.02);
|
||||
if (!rhi.isEmpty()) lines.addAll(rhi);
|
||||
}
|
||||
|
||||
private static void appendRhiCounters(List<String> lines) {
|
||||
RhiStatsSnapshot rhi = LoVisualRenderSystem.rhiStatsSnapshot();
|
||||
UniformAllocatorStatsSnapshot uniforms = LoVisualRenderSystem.uniformStatsSnapshot();
|
||||
if (rhi.drawCalls() > 0 || rhi.renderPasses() > 0 || rhi.meshUploads() > 0 || rhi.fullscreenPasses() > 0
|
||||
|| rhi.textureFastCopies() > 0 || rhi.textureShaderCopies() > 0) {
|
||||
lines.add(String.format(
|
||||
"rhi: draws %d, passes/switches %d/%d, meshUploads %d, fullscreen %d, copies fast/shader %d/%d, uploaded v/i %s/%s",
|
||||
rhi.drawCalls(),
|
||||
rhi.renderPasses(),
|
||||
rhi.renderPassAttachmentSwitches(),
|
||||
rhi.meshUploads(),
|
||||
rhi.fullscreenPasses(),
|
||||
rhi.textureFastCopies(),
|
||||
rhi.textureShaderCopies(),
|
||||
formatBytes(rhi.uploadedVertexBytes()),
|
||||
formatBytes(rhi.uploadedIndexBytes())
|
||||
));
|
||||
}
|
||||
if (rhi.ringWraps() > 0 || rhi.ringStalls() > 0 || rhi.immediateFallbackUploads() > 0) {
|
||||
lines.add(String.format(
|
||||
"rhi upload: wraps %d, stalls %d, immediateFallback %d, arena reuse/retire %d/%d",
|
||||
rhi.ringWraps(),
|
||||
rhi.ringStalls(),
|
||||
rhi.immediateFallbackUploads(),
|
||||
rhi.dynamicArenaReuses(),
|
||||
rhi.dynamicArenaRetires()
|
||||
));
|
||||
}
|
||||
if (rhi.legacyPathUses() > 0) {
|
||||
lines.add("rhi legacy paths: " + rhi.legacyPathUses() + " " + rhi.legacyPathBreakdown());
|
||||
}
|
||||
if (uniforms.writes() > 0 || uniforms.ringRotations() > 0 || uniforms.staleReadMisses() > 0) {
|
||||
lines.add(String.format(
|
||||
"uniforms: writes %d, bytes %s, activeStreams %d, rotations %d, grows %d, staleMiss %d",
|
||||
uniforms.writes(),
|
||||
formatBytes(uniforms.uploadedBytes()),
|
||||
uniforms.activeStreams(),
|
||||
uniforms.ringRotations(),
|
||||
uniforms.ringGrows(),
|
||||
uniforms.staleReadMisses()
|
||||
));
|
||||
}
|
||||
RenderResourceStatsSnapshot resources = LoVisualRenderSystem.resourceStatsSnapshot();
|
||||
if (resources.persistentFramebuffers() > 0 || resources.temporaryFramebuffers() > 0
|
||||
|| resources.retirementBacklog() > 0 || resources.leakedResources() > 0) {
|
||||
lines.add(String.format(
|
||||
"resources: fb persistent/temp %d/%d, create/resize %d/%d, borrow/release %d/%d, retire backlog/leaks %d/%d",
|
||||
resources.persistentFramebuffers(),
|
||||
resources.temporaryFramebuffers(),
|
||||
resources.framebufferCreates(),
|
||||
resources.framebufferResizes(),
|
||||
resources.framebufferBorrows(),
|
||||
resources.framebufferReleases(),
|
||||
resources.retirementBacklog(),
|
||||
resources.leakedResources()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private static String formatBytes(long bytes) {
|
||||
if (bytes < 1024L) return bytes + " B";
|
||||
double kb = bytes / 1024.0;
|
||||
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
|
||||
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
|
||||
}
|
||||
|
||||
private static void collectFlat(Node node, List<Node> out) {
|
||||
for (Node child : node.children.values()) {
|
||||
out.add(child);
|
||||
collectFlat(child, out);
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendTreeAscii(List<String> out, Node node, String indent, int depth, int maxDepth, double minMs) {
|
||||
if (node == null) return;
|
||||
double ms = node.totalNs / (double) NS_IN_MS;
|
||||
if (depth > 0 && ms < minMs) return;
|
||||
double selfMs = selfNs(node) / (double) NS_IN_MS;
|
||||
String line = depth == 0
|
||||
? String.format("%s %.2f ms (self %.2f, %d)", node.name, ms, selfMs, node.calls)
|
||||
: String.format("%s|-- %s %.2f ms (self %.2f, %d)", indent, node.name, ms, selfMs, node.calls);
|
||||
out.add(line);
|
||||
if (depth >= maxDepth) return;
|
||||
List<Node> children = new ArrayList<>(node.children.values());
|
||||
children.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
|
||||
String childIndent = indent + "| ";
|
||||
for (Node child : children) {
|
||||
appendTreeAscii(out, child, childIndent, depth + 1, maxDepth, minMs);
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitIfDue(long nowNs) {
|
||||
ProfilerSettings.OutputMode mode = getOutputMode();
|
||||
if (mode == ProfilerSettings.OutputMode.OFF) return;
|
||||
|
||||
if (nowNs - lastEmitNs < DEFAULT_EMIT_INTERVAL_NS) return;
|
||||
lastEmitNs = nowNs;
|
||||
|
||||
if (mode == ProfilerSettings.OutputMode.LOG) {
|
||||
emitToLog();
|
||||
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
|
||||
emitToChat();
|
||||
}
|
||||
}
|
||||
|
||||
private static ProfilerSettings.OutputMode getOutputMode() {
|
||||
if (!isEnabled()) return ProfilerSettings.OutputMode.OFF;
|
||||
return getOutputModeRaw();
|
||||
}
|
||||
|
||||
private static ProfilerSettings.OutputMode getOutputModeRaw() {
|
||||
return ProfilerSettings.getOutput2d();
|
||||
}
|
||||
|
||||
private static void emitToLog() {
|
||||
List<String> lines = getDebugLines();
|
||||
if (lines.isEmpty()) return;
|
||||
for (String line : lines) {
|
||||
ProfilerLog.info("[UIProfiler] %s", line);
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitToChat() {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.gui == null) return;
|
||||
List<String> lines = getDebugLines(4, 2, 0.05);
|
||||
if (lines.isEmpty()) return;
|
||||
for (String line : lines) {
|
||||
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[UIProfiler] " + line));
|
||||
}
|
||||
}
|
||||
|
||||
private static long selfNs(Node node) {
|
||||
if (node == null) return 0L;
|
||||
long childrenNs = 0L;
|
||||
for (Node child : node.children.values()) {
|
||||
childrenNs += child.totalNs;
|
||||
}
|
||||
long self = node.totalNs - childrenNs;
|
||||
return Math.max(0L, self);
|
||||
}
|
||||
|
||||
private static Node hottestChild(Node node) {
|
||||
if (node == null || node.children.isEmpty()) return null;
|
||||
Node best = null;
|
||||
long bestNs = 0L;
|
||||
for (Node child : node.children.values()) {
|
||||
if (best == null || child.totalNs > bestNs) {
|
||||
best = child;
|
||||
bestNs = child.totalNs;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static String nodePath(Node node) {
|
||||
if (node == null) return "";
|
||||
List<String> parts = new ArrayList<>();
|
||||
Node cur = node;
|
||||
while (cur != null) {
|
||||
parts.add(cur.name);
|
||||
cur = cur.parent;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = parts.size() - 1; i >= 0; i--) {
|
||||
if (sb.length() > 0) sb.append(" > ");
|
||||
sb.append(parts.get(i));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static final class Section implements AutoCloseable {
|
||||
private static final Section NOOP = new Section(false);
|
||||
private final boolean active;
|
||||
|
||||
private Section(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!active) return;
|
||||
endSection();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Node {
|
||||
final String name;
|
||||
final Node parent;
|
||||
final Map<String, Node> children = new HashMap<>();
|
||||
long totalNs;
|
||||
long startNs;
|
||||
int calls;
|
||||
|
||||
private Node(String name, Node parent) {
|
||||
this.name = name;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
int countNodes() {
|
||||
int count = 1;
|
||||
for (Node child : children.values()) {
|
||||
count += child.countNodes();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,420 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
|
||||
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.world.WorldRenderStatsSnapshot;
|
||||
import dev.loki.lovisual.render.iris.IrisRuntimeSnapshot;
|
||||
import dev.loki.lovisual.render.sodium.SodiumTerrainInteropStatsSnapshot;
|
||||
import dev.loki.lovisual.render.sodium.SodiumVisibilityStatsSnapshot;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public enum DevRenderProfiler3D {
|
||||
;
|
||||
|
||||
private static final long NS_IN_MS = 1_000_000L;
|
||||
private static final int DEFAULT_TOP_LIMIT = 6;
|
||||
private static final int DEFAULT_TREE_DEPTH = 32;
|
||||
private static final double DEFAULT_MIN_MS = 0.0;
|
||||
private static final long DEFAULT_EMIT_INTERVAL_NS = 1_000_000_000L;
|
||||
private static final ArrayDeque<Node> stack = new ArrayDeque<>();
|
||||
private static boolean active;
|
||||
private static Node root;
|
||||
private static Node snapshot;
|
||||
private static long lastEmitNs;
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
|
||||
}
|
||||
|
||||
public static void beginFrame(String name) {
|
||||
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.WORLD);
|
||||
if (!isEnabled()) return;
|
||||
active = true;
|
||||
root = new Node(name, null);
|
||||
stack.clear();
|
||||
stack.push(root);
|
||||
root.startNs = System.nanoTime();
|
||||
}
|
||||
|
||||
public static boolean beginFrameIfNeeded(String name) {
|
||||
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.WORLD);
|
||||
if (!isEnabled() || active) return false;
|
||||
beginFrame(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void endFrame() {
|
||||
if (!isEnabled() || !active) return;
|
||||
long now = System.nanoTime();
|
||||
while (stack.size() > 1) {
|
||||
endSection();
|
||||
}
|
||||
Node r = stack.peek();
|
||||
if (r != null) {
|
||||
r.calls = Math.max(1, r.calls);
|
||||
r.totalNs += now - r.startNs;
|
||||
r.startNs = 0L;
|
||||
snapshot = r;
|
||||
DevTracyProfiler.plotWorldFrame(r.totalNs / (double) NS_IN_MS, r.countNodes());
|
||||
}
|
||||
active = false;
|
||||
emitIfDue(now);
|
||||
}
|
||||
|
||||
public static Section section(String name) {
|
||||
if (!isEnabled() || !active) return Section.NOOP;
|
||||
beginSection(name);
|
||||
return new Section(true);
|
||||
}
|
||||
|
||||
private static void beginSection(String name) {
|
||||
Node parent = stack.peek();
|
||||
if (parent == null) return;
|
||||
Node child = parent.children.computeIfAbsent(name, n -> new Node(n, parent));
|
||||
child.calls += 1;
|
||||
child.startNs = System.nanoTime();
|
||||
stack.push(child);
|
||||
}
|
||||
|
||||
private static void endSection() {
|
||||
Node node = stack.poll();
|
||||
if (node == null) return;
|
||||
long now = System.nanoTime();
|
||||
node.totalNs += now - node.startNs;
|
||||
node.startNs = 0L;
|
||||
}
|
||||
|
||||
public static List<String> getDebugLines() {
|
||||
return getDebugLines(DEFAULT_TOP_LIMIT, DEFAULT_TREE_DEPTH, DEFAULT_MIN_MS);
|
||||
}
|
||||
|
||||
public static List<String> getDebugLines(int topLimit, int depthLimit, double minMs) {
|
||||
if (!isEnabled()) return List.of();
|
||||
Node snap = snapshot;
|
||||
if (snap == null) return List.of();
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
double totalMs = snap.totalNs / (double) NS_IN_MS;
|
||||
lines.add(String.format("world prof: %.2f ms, nodes %d", totalMs, snap.countNodes()));
|
||||
appendRhiCounters(lines);
|
||||
appendCostCounters(lines);
|
||||
|
||||
List<Node> flat = new ArrayList<>();
|
||||
collectFlat(snap, flat);
|
||||
flat.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
|
||||
|
||||
int top = Math.min(topLimit, flat.size());
|
||||
if (top > 0) {
|
||||
lines.add("world prof top:");
|
||||
for (int i = 0; i < top; i++) {
|
||||
Node n = flat.get(i);
|
||||
double ms = n.totalNs / (double) NS_IN_MS;
|
||||
if (ms < minMs) break;
|
||||
double selfMs = selfNs(n) / (double) NS_IN_MS;
|
||||
Node hot = hottestChild(n);
|
||||
if (hot != null) {
|
||||
double hotMs = hot.totalNs / (double) NS_IN_MS;
|
||||
lines.add(String.format(
|
||||
" %d) %s %.2f ms (self %.2f, hot %s %.2f, %d)",
|
||||
i + 1,
|
||||
nodePath(n),
|
||||
ms,
|
||||
selfMs,
|
||||
hot.name,
|
||||
hotMs,
|
||||
n.calls
|
||||
));
|
||||
} else {
|
||||
lines.add(String.format(
|
||||
" %d) %s %.2f ms (self %.2f, %d)",
|
||||
i + 1,
|
||||
nodePath(n),
|
||||
ms,
|
||||
selfMs,
|
||||
n.calls
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.add("world prof tree:");
|
||||
appendTreeAscii(lines, snap, "", 0, depthLimit, minMs);
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static void appendCostCounters(List<String> lines) {
|
||||
List<String> phase = DevRenderCostProfiler.debugLines("render cost phases", "phase", 6, 0.02);
|
||||
if (!phase.isEmpty()) lines.addAll(phase);
|
||||
List<String> post = DevRenderCostProfiler.debugLines("world cost post", "post.pass", 8, 0.02);
|
||||
if (!post.isEmpty()) lines.addAll(post);
|
||||
List<String> effects = DevRenderCostProfiler.debugLines("world cost effects", "world.effect", 8, 0.02);
|
||||
if (!effects.isEmpty()) lines.addAll(effects);
|
||||
List<String> rhi = DevRenderCostProfiler.debugLines("world cost rhi draws", "rhi.draw", 8, 0.02);
|
||||
if (!rhi.isEmpty()) lines.addAll(rhi);
|
||||
}
|
||||
|
||||
private static void appendRhiCounters(List<String> lines) {
|
||||
RhiStatsSnapshot rhi = LoVisualRenderSystem.rhiStatsSnapshot();
|
||||
UniformAllocatorStatsSnapshot uniforms = LoVisualRenderSystem.uniformStatsSnapshot();
|
||||
if (rhi.drawCalls() > 0 || rhi.renderPasses() > 0 || rhi.meshUploads() > 0 || rhi.fullscreenPasses() > 0
|
||||
|| rhi.textureFastCopies() > 0 || rhi.textureShaderCopies() > 0) {
|
||||
lines.add(String.format(
|
||||
"rhi: draws %d, passes/switches %d/%d, meshUploads %d, fullscreen %d, copies fast/shader %d/%d, uploaded v/i %s/%s",
|
||||
rhi.drawCalls(),
|
||||
rhi.renderPasses(),
|
||||
rhi.renderPassAttachmentSwitches(),
|
||||
rhi.meshUploads(),
|
||||
rhi.fullscreenPasses(),
|
||||
rhi.textureFastCopies(),
|
||||
rhi.textureShaderCopies(),
|
||||
formatBytes(rhi.uploadedVertexBytes()),
|
||||
formatBytes(rhi.uploadedIndexBytes())
|
||||
));
|
||||
}
|
||||
WorldRenderStatsSnapshot world = LoVisualRenderSystem.worldRenderStatsSnapshot();
|
||||
if (world.recordedCommands() > 0 || world.submittedCommands() > 0 || world.skippedEmptyCommands() > 0) {
|
||||
lines.add(String.format(
|
||||
"world3d: commands rec/sub/skip %d/%d/%d, vertices/indices %d/%d, fog %d, depth pre/main/none %d/%d/%d",
|
||||
world.recordedCommands(),
|
||||
world.submittedCommands(),
|
||||
world.skippedEmptyCommands(),
|
||||
world.submittedVertices(),
|
||||
world.submittedIndices(),
|
||||
world.fogBindings(),
|
||||
world.depthPrePassBindings(),
|
||||
world.depthMainBindings(),
|
||||
world.depthDisabledBindings()
|
||||
));
|
||||
}
|
||||
|
||||
if (rhi.ringWraps() > 0 || rhi.ringStalls() > 0 || rhi.immediateFallbackUploads() > 0) {
|
||||
lines.add(String.format(
|
||||
"rhi upload: wraps %d, stalls %d, immediateFallback %d, arena reuse/retire %d/%d",
|
||||
rhi.ringWraps(),
|
||||
rhi.ringStalls(),
|
||||
rhi.immediateFallbackUploads(),
|
||||
rhi.dynamicArenaReuses(),
|
||||
rhi.dynamicArenaRetires()
|
||||
));
|
||||
}
|
||||
if (rhi.legacyPathUses() > 0) {
|
||||
lines.add("rhi legacy paths: " + rhi.legacyPathUses() + " " + rhi.legacyPathBreakdown());
|
||||
}
|
||||
if (uniforms.writes() > 0 || uniforms.ringRotations() > 0 || uniforms.staleReadMisses() > 0) {
|
||||
lines.add(String.format(
|
||||
"uniforms: writes %d, bytes %s, activeStreams %d, rotations %d, grows %d, staleMiss %d",
|
||||
uniforms.writes(),
|
||||
formatBytes(uniforms.uploadedBytes()),
|
||||
uniforms.activeStreams(),
|
||||
uniforms.ringRotations(),
|
||||
uniforms.ringGrows(),
|
||||
uniforms.staleReadMisses()
|
||||
));
|
||||
}
|
||||
RenderResourceStatsSnapshot resources = LoVisualRenderSystem.resourceStatsSnapshot();
|
||||
if (resources.persistentFramebuffers() > 0 || resources.temporaryFramebuffers() > 0
|
||||
|| resources.retirementBacklog() > 0 || resources.leakedResources() > 0) {
|
||||
lines.add(String.format(
|
||||
"resources: fb persistent/temp %d/%d, create/resize %d/%d, borrow/release %d/%d, retire backlog/leaks %d/%d",
|
||||
resources.persistentFramebuffers(),
|
||||
resources.temporaryFramebuffers(),
|
||||
resources.framebufferCreates(),
|
||||
resources.framebufferResizes(),
|
||||
resources.framebufferBorrows(),
|
||||
resources.framebufferReleases(),
|
||||
resources.retirementBacklog(),
|
||||
resources.leakedResources()
|
||||
));
|
||||
}
|
||||
|
||||
IrisRuntimeSnapshot iris = LoVisualRenderSystem.irisSnapshot();
|
||||
if (iris.modLoaded() || iris.shaderpackInUse()) {
|
||||
lines.add(iris.shortLine());
|
||||
}
|
||||
|
||||
var immediatelyFast = LoVisualRenderSystem.immediatelyFastSnapshot();
|
||||
if (immediatelyFast.modLoaded()) {
|
||||
lines.add(immediatelyFast.shortLine());
|
||||
}
|
||||
|
||||
SodiumVisibilityStatsSnapshot sodiumVisibility = LoVisualRenderSystem.sodiumVisibilityStatsSnapshot();
|
||||
if (sodiumVisibility.queries() > 0 || sodiumVisibility.errors() > 0) {
|
||||
lines.add(String.format(
|
||||
"sodium vis: queries %d, accepts/rejects %d/%d, bypass %d (unavail %d, optout %d), errors %d",
|
||||
sodiumVisibility.queries(),
|
||||
sodiumVisibility.accepts(),
|
||||
sodiumVisibility.rejects(),
|
||||
sodiumVisibility.bypasses(),
|
||||
sodiumVisibility.unavailableBypasses(),
|
||||
sodiumVisibility.optOutBypasses(),
|
||||
sodiumVisibility.errors()
|
||||
));
|
||||
}
|
||||
|
||||
SodiumTerrainInteropStatsSnapshot sodiumTerrain = LoVisualRenderSystem.sodiumTerrainStatsSnapshot();
|
||||
if (sodiumTerrain.terrainUpdatesScheduled() > 0
|
||||
|| sodiumTerrain.rebuildsScheduled() > 0
|
||||
|| sodiumTerrain.interopErrors() > 0) {
|
||||
lines.add(String.format(
|
||||
"sodium terrain: updates %d, rebuilds %d, errors %d",
|
||||
sodiumTerrain.terrainUpdatesScheduled(),
|
||||
sodiumTerrain.rebuildsScheduled(),
|
||||
sodiumTerrain.interopErrors()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private static String formatBytes(long bytes) {
|
||||
if (bytes < 1024L) return bytes + " B";
|
||||
double kb = bytes / 1024.0;
|
||||
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
|
||||
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
|
||||
}
|
||||
|
||||
private static void collectFlat(Node node, List<Node> out) {
|
||||
for (Node child : node.children.values()) {
|
||||
out.add(child);
|
||||
collectFlat(child, out);
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendTreeAscii(List<String> out, Node node, String indent, int depth, int maxDepth, double minMs) {
|
||||
if (node == null) return;
|
||||
double ms = node.totalNs / (double) NS_IN_MS;
|
||||
if (depth > 0 && ms < minMs) return;
|
||||
double selfMs = selfNs(node) / (double) NS_IN_MS;
|
||||
String line = depth == 0
|
||||
? String.format("%s %.2f ms (self %.2f, %d)", node.name, ms, selfMs, node.calls)
|
||||
: String.format("%s|-- %s %.2f ms (self %.2f, %d)", indent, node.name, ms, selfMs, node.calls);
|
||||
out.add(line);
|
||||
if (depth >= maxDepth) return;
|
||||
List<Node> children = new ArrayList<>(node.children.values());
|
||||
children.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
|
||||
String childIndent = indent + "| ";
|
||||
for (Node child : children) {
|
||||
appendTreeAscii(out, child, childIndent, depth + 1, maxDepth, minMs);
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitIfDue(long nowNs) {
|
||||
ProfilerSettings.OutputMode mode = getOutputMode();
|
||||
if (mode == ProfilerSettings.OutputMode.OFF) return;
|
||||
|
||||
if (nowNs - lastEmitNs < DEFAULT_EMIT_INTERVAL_NS) return;
|
||||
lastEmitNs = nowNs;
|
||||
|
||||
if (mode == ProfilerSettings.OutputMode.LOG) {
|
||||
emitToLog();
|
||||
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
|
||||
emitToChat();
|
||||
}
|
||||
}
|
||||
|
||||
private static ProfilerSettings.OutputMode getOutputMode() {
|
||||
if (!isEnabled()) return ProfilerSettings.OutputMode.OFF;
|
||||
return getOutputModeRaw();
|
||||
}
|
||||
|
||||
private static ProfilerSettings.OutputMode getOutputModeRaw() {
|
||||
return ProfilerSettings.getOutput3d();
|
||||
}
|
||||
|
||||
private static void emitToLog() {
|
||||
List<String> lines = getDebugLines();
|
||||
if (lines.isEmpty()) return;
|
||||
for (String line : lines) {
|
||||
ProfilerLog.info("[WorldProfiler] %s", line);
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitToChat() {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.gui == null) return;
|
||||
List<String> lines = getDebugLines(4, 2, 0.05);
|
||||
if (lines.isEmpty()) return;
|
||||
for (String line : lines) {
|
||||
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[WorldProfiler] " + line));
|
||||
}
|
||||
}
|
||||
|
||||
private static long selfNs(Node node) {
|
||||
if (node == null) return 0L;
|
||||
long childrenNs = 0L;
|
||||
for (Node child : node.children.values()) {
|
||||
childrenNs += child.totalNs;
|
||||
}
|
||||
long self = node.totalNs - childrenNs;
|
||||
return Math.max(0L, self);
|
||||
}
|
||||
|
||||
private static Node hottestChild(Node node) {
|
||||
if (node == null || node.children.isEmpty()) return null;
|
||||
Node best = null;
|
||||
long bestNs = 0L;
|
||||
for (Node child : node.children.values()) {
|
||||
if (best == null || child.totalNs > bestNs) {
|
||||
best = child;
|
||||
bestNs = child.totalNs;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static String nodePath(Node node) {
|
||||
if (node == null) return "";
|
||||
List<String> parts = new ArrayList<>();
|
||||
Node cur = node;
|
||||
while (cur != null) {
|
||||
parts.add(cur.name);
|
||||
cur = cur.parent;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = parts.size() - 1; i >= 0; i--) {
|
||||
if (sb.length() > 0) sb.append(" > ");
|
||||
sb.append(parts.get(i));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static final class Section implements AutoCloseable {
|
||||
private static final Section NOOP = new Section(false);
|
||||
private final boolean active;
|
||||
|
||||
private Section(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!active) return;
|
||||
endSection();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Node {
|
||||
final String name;
|
||||
final Node parent;
|
||||
final Map<String, Node> children = new HashMap<>();
|
||||
long totalNs;
|
||||
long startNs;
|
||||
int calls;
|
||||
|
||||
private Node(String name, Node parent) {
|
||||
this.name = name;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
int countNodes() {
|
||||
int count = 1;
|
||||
for (Node child : children.values()) {
|
||||
count += child.countNodes();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,442 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public enum DevSamplingProfiler {
|
||||
;
|
||||
|
||||
private static final long SAMPLE_INTERVAL_NS = 10_000_000L; // 10 ms
|
||||
private static final long EMIT_INTERVAL_NS = 1_000_000_000L; // 1 s
|
||||
private static final int TOP_LIMIT = 8;
|
||||
private static final int TOP_LIMIT_NON_GL = 4;
|
||||
private static final int TOP_LIMIT_GL_WAIT = 3;
|
||||
private static final int MAX_STACK_FRAMES = 4;
|
||||
private static final int MAX_ENTRIES = 256;
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
private static final Map<String, Integer> COUNTS = new HashMap<>();
|
||||
private static int idleSamples;
|
||||
|
||||
private static volatile Thread targetThread;
|
||||
private static volatile Thread samplerThread;
|
||||
private static volatile boolean running;
|
||||
private static volatile long lastEmitNs;
|
||||
private static volatile List<String> pendingChatLines;
|
||||
private static volatile Target lastSource = Target.WORLD;
|
||||
|
||||
public static void onClientFrame(Target source) {
|
||||
if (!isEnabled()) {
|
||||
DevProfilerPhase.clearCurrent();
|
||||
stopIfRunning();
|
||||
return;
|
||||
}
|
||||
|
||||
lastSource = source;
|
||||
flushPendingChat();
|
||||
if (!matchesTarget(source)) return;
|
||||
targetThread = Thread.currentThread();
|
||||
ensureRunning();
|
||||
}
|
||||
|
||||
private static boolean isEnabled() {
|
||||
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
|
||||
}
|
||||
|
||||
public static boolean isActive() {
|
||||
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
|
||||
}
|
||||
|
||||
private static void ensureRunning() {
|
||||
if (running) return;
|
||||
running = true;
|
||||
samplerThread = new Thread(DevSamplingProfiler::runLoop, "LoVisual-DevSamplingProfiler");
|
||||
samplerThread.setDaemon(true);
|
||||
samplerThread.start();
|
||||
}
|
||||
|
||||
private static void stopIfRunning() {
|
||||
if (!running) return;
|
||||
running = false;
|
||||
Thread t = samplerThread;
|
||||
samplerThread = null;
|
||||
if (t != null) t.interrupt();
|
||||
synchronized (LOCK) {
|
||||
COUNTS.clear();
|
||||
idleSamples = 0;
|
||||
}
|
||||
DevGlSyncTracker.reset();
|
||||
pendingChatLines = null;
|
||||
}
|
||||
|
||||
private static void runLoop() {
|
||||
long lastSampleNs = 0L;
|
||||
while (running) {
|
||||
if (!isEnabled()) {
|
||||
running = false;
|
||||
synchronized (LOCK) {
|
||||
COUNTS.clear();
|
||||
idleSamples = 0;
|
||||
}
|
||||
DevGlSyncTracker.reset();
|
||||
pendingChatLines = null;
|
||||
break;
|
||||
}
|
||||
Thread t = targetThread;
|
||||
if (t == null) {
|
||||
sleepMs(10);
|
||||
continue;
|
||||
}
|
||||
long now = System.nanoTime();
|
||||
if (now - lastSampleNs >= SAMPLE_INTERVAL_NS) {
|
||||
if (matchesTarget(lastSource)) {
|
||||
sample(t);
|
||||
}
|
||||
lastSampleNs = now;
|
||||
}
|
||||
if (now - lastEmitNs >= EMIT_INTERVAL_NS) {
|
||||
emit(now);
|
||||
}
|
||||
sleepMs(2);
|
||||
}
|
||||
}
|
||||
|
||||
private static void sample(Thread t) {
|
||||
StackTraceElement[] stack = t.getStackTrace();
|
||||
if (stack == null || stack.length == 0) return;
|
||||
if (isIdleStack(stack)) {
|
||||
synchronized (LOCK) {
|
||||
idleSamples += 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
String key = buildKey(stack);
|
||||
if (key == null || key.isEmpty()) return;
|
||||
synchronized (LOCK) {
|
||||
COUNTS.merge(key, 1, Integer::sum);
|
||||
if (COUNTS.size() > MAX_ENTRIES) {
|
||||
trimToLimit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void emit(long now) {
|
||||
ProfilerSettings.OutputMode mode = getOutputModeRaw();
|
||||
if (mode == ProfilerSettings.OutputMode.OFF) return;
|
||||
List<String> lines = buildOutputLines();
|
||||
if (lines.isEmpty()) return;
|
||||
lastEmitNs = now;
|
||||
|
||||
if (mode == ProfilerSettings.OutputMode.LOG) {
|
||||
for (String line : lines) {
|
||||
ProfilerLog.info("[SampleProfiler] %s", line);
|
||||
}
|
||||
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
|
||||
pendingChatLines = lines;
|
||||
}
|
||||
|
||||
synchronized (LOCK) {
|
||||
COUNTS.clear();
|
||||
idleSamples = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> buildOutputLines() {
|
||||
List<Map.Entry<String, Integer>> entries;
|
||||
int total;
|
||||
int idle;
|
||||
synchronized (LOCK) {
|
||||
if (COUNTS.isEmpty() && idleSamples == 0) return List.of();
|
||||
entries = new ArrayList<>(COUNTS.entrySet());
|
||||
int sum = 0;
|
||||
for (Integer count : COUNTS.values()) {
|
||||
if (count != null) {
|
||||
sum += count;
|
||||
}
|
||||
}
|
||||
total = sum;
|
||||
idle = idleSamples;
|
||||
}
|
||||
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
int all = total + idle;
|
||||
double idlePct = all == 0 ? 0.0 : (idle * 100.0) / all;
|
||||
lines.add(String.format("sample prof: %d samples, idle %d (%.1f%%), entries %d", all, idle, idlePct, entries.size()));
|
||||
|
||||
int glWait = 0;
|
||||
int glUpload = 0;
|
||||
int glDraw = 0;
|
||||
int glState = 0;
|
||||
int glWaitClient = 0;
|
||||
int glWaitSwap = 0;
|
||||
int glWaitFinish = 0;
|
||||
int glWaitSync = 0;
|
||||
int glWaitOther = 0;
|
||||
|
||||
List<Map.Entry<String, Integer>> nonGl = new ArrayList<>();
|
||||
List<Map.Entry<String, Integer>> glWaitList = new ArrayList<>();
|
||||
for (Map.Entry<String, Integer> e : entries) {
|
||||
String k = e.getKey();
|
||||
int c = e.getValue();
|
||||
if (k.startsWith("GL WAIT:")) {
|
||||
glWait += c;
|
||||
glWaitList.add(e);
|
||||
if (containsAny(k, "glClientWaitSync", "nglClientWaitSync")) {
|
||||
glWaitClient += c;
|
||||
} else if (containsAny(k, "glfwSwapBuffers")) {
|
||||
glWaitSwap += c;
|
||||
} else if (containsAny(k, "glFinish", "nglFinish")) {
|
||||
glWaitFinish += c;
|
||||
} else if (containsAny(k, "glWaitSync", "nglWaitSync")) {
|
||||
glWaitSync += c;
|
||||
} else {
|
||||
glWaitOther += c;
|
||||
}
|
||||
} else if (k.startsWith("GL UPLOAD:")) {
|
||||
glUpload += c;
|
||||
} else if (k.startsWith("GL DRAW:")) {
|
||||
glDraw += c;
|
||||
} else if (k.startsWith("GL STATE:")) {
|
||||
glState += c;
|
||||
} else {
|
||||
nonGl.add(e);
|
||||
}
|
||||
}
|
||||
int glTotal = glWait + glUpload + glDraw + glState;
|
||||
if (glTotal > 0) {
|
||||
double waitPct = all == 0 ? 0.0 : (glWait * 100.0) / all;
|
||||
double uploadPct = all == 0 ? 0.0 : (glUpload * 100.0) / all;
|
||||
double drawPct = all == 0 ? 0.0 : (glDraw * 100.0) / all;
|
||||
double statePct = all == 0 ? 0.0 : (glState * 100.0) / all;
|
||||
lines.add(String.format(
|
||||
"gl samples: wait %d (%.1f%%), upload %d (%.1f%%), draw %d (%.1f%%), state %d (%.1f%%)",
|
||||
glWait, waitPct, glUpload, uploadPct, glDraw, drawPct, glState, statePct
|
||||
));
|
||||
if (glWait > 0) {
|
||||
lines.add(String.format(
|
||||
"gl wait breakdown: client %d, swap %d, finish %d, waitsync %d, other %d",
|
||||
glWaitClient, glWaitSwap, glWaitFinish, glWaitSync, glWaitOther
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
List<String> waitPhaseLines = DevGlSyncTracker.drainLines();
|
||||
if (!waitPhaseLines.isEmpty()) {
|
||||
lines.addAll(waitPhaseLines);
|
||||
}
|
||||
lines.add("sample prof top:");
|
||||
|
||||
int top = Math.min(TOP_LIMIT, entries.size());
|
||||
for (int i = 0; i < top; i++) {
|
||||
Map.Entry<String, Integer> e = entries.get(i);
|
||||
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
|
||||
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
|
||||
}
|
||||
|
||||
if (!nonGl.isEmpty()) {
|
||||
int topNon = Math.min(TOP_LIMIT_NON_GL, nonGl.size());
|
||||
lines.add("sample prof top non-gl:");
|
||||
for (int i = 0; i < topNon; i++) {
|
||||
Map.Entry<String, Integer> e = nonGl.get(i);
|
||||
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
|
||||
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
|
||||
}
|
||||
}
|
||||
|
||||
if (!glWaitList.isEmpty()) {
|
||||
int topWait = Math.min(TOP_LIMIT_GL_WAIT, glWaitList.size());
|
||||
lines.add("sample prof top gl wait:");
|
||||
for (int i = 0; i < topWait; i++) {
|
||||
Map.Entry<String, Integer> e = glWaitList.get(i);
|
||||
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
|
||||
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static void flushPendingChat() {
|
||||
List<String> lines = pendingChatLines;
|
||||
if (lines == null || lines.isEmpty()) return;
|
||||
pendingChatLines = null;
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.gui == null) return;
|
||||
for (String line : lines) {
|
||||
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[SampleProfiler] " + line));
|
||||
}
|
||||
}
|
||||
|
||||
private static String buildKey(StackTraceElement[] stack) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String glCat = glCategory(stack);
|
||||
boolean hasPrefix = false;
|
||||
if (glCat != null) {
|
||||
sb.append("GL ").append(glCat).append(": ");
|
||||
hasPrefix = true;
|
||||
}
|
||||
int added = 0;
|
||||
for (StackTraceElement e : stack) {
|
||||
if (added >= MAX_STACK_FRAMES) break;
|
||||
if (isNoise(e)) continue;
|
||||
if (added > 0 || (sb.length() > 0 && !hasPrefix)) sb.append(" <= ");
|
||||
sb.append(formatElement(e));
|
||||
added++;
|
||||
}
|
||||
return added == 0 ? null : sb.toString();
|
||||
}
|
||||
|
||||
private static boolean isNoise(StackTraceElement e) {
|
||||
String cls = e.getClassName();
|
||||
return cls.startsWith("java.lang.Thread")
|
||||
|| cls.startsWith("java.util.concurrent")
|
||||
|| cls.startsWith("jdk.internal")
|
||||
|| cls.startsWith("sun.")
|
||||
|| cls.startsWith("dev.loki.lovisual.render.engine.profiler.DevSamplingProfiler");
|
||||
}
|
||||
|
||||
private static String glCategory(StackTraceElement[] stack) {
|
||||
for (StackTraceElement e : stack) {
|
||||
String cls = e.getClassName();
|
||||
String method = e.getMethodName();
|
||||
if (!isGlFrame(cls)) continue;
|
||||
String cat = glCategoryForMethod(method);
|
||||
if (cat != null) return cat;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isGlFrame(String cls) {
|
||||
if (cls == null) return false;
|
||||
return cls.startsWith("org.lwjgl.opengl.")
|
||||
|| cls.startsWith("org.lwjgl.glfw.")
|
||||
|| cls.startsWith("com.mojang.blaze3d.platform.")
|
||||
|| cls.startsWith("com.mojang.blaze3d.systems.");
|
||||
}
|
||||
|
||||
private static String glCategoryForMethod(String method) {
|
||||
if (method == null) return null;
|
||||
if (method.equals("glfwSwapBuffers")
|
||||
|| method.equals("glClientWaitSync")
|
||||
|| method.equals("glWaitSync")
|
||||
|| method.equals("glFinish")) {
|
||||
return "WAIT";
|
||||
}
|
||||
if (method.startsWith("glDraw") || method.startsWith("glMultiDraw")) {
|
||||
return "DRAW";
|
||||
}
|
||||
if (method.contains("BufferSubData")
|
||||
|| method.contains("BufferData")
|
||||
|| method.contains("TexImage")
|
||||
|| method.contains("TexSubImage")
|
||||
|| method.contains("CompressedTex")
|
||||
|| method.contains("FlushMapped")
|
||||
|| method.contains("MapBuffer")
|
||||
|| method.contains("MapBufferRange")
|
||||
|| method.contains("UnmapBuffer")) {
|
||||
return "UPLOAD";
|
||||
}
|
||||
if (method.startsWith("glUseProgram")
|
||||
|| method.startsWith("glBind")
|
||||
|| method.startsWith("glTexParameter")
|
||||
|| method.startsWith("glBlendFunc")
|
||||
|| method.startsWith("glBlendEquation")
|
||||
|| method.startsWith("glEnable")
|
||||
|| method.startsWith("glDisable")
|
||||
|| method.startsWith("glDepthFunc")
|
||||
|| method.startsWith("glDepthMask")
|
||||
|| method.startsWith("glColorMask")
|
||||
|| method.startsWith("glCullFace")
|
||||
|| method.startsWith("glFrontFace")
|
||||
|| method.startsWith("glViewport")
|
||||
|| method.startsWith("glScissor")
|
||||
|| method.startsWith("glPolygonMode")
|
||||
|| method.startsWith("glActiveTexture")
|
||||
|| method.startsWith("glUniform")
|
||||
|| method.startsWith("glVertexAttrib")) {
|
||||
return "STATE";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean containsAny(String text, String... needles) {
|
||||
if (text == null) return false;
|
||||
for (String n : needles) {
|
||||
if (n != null && !n.isEmpty() && text.contains(n)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isIdleStack(StackTraceElement[] stack) {
|
||||
boolean hasWait = false;
|
||||
boolean hasLimit = false;
|
||||
for (StackTraceElement e : stack) {
|
||||
String cls = e.getClassName();
|
||||
String method = e.getMethodName();
|
||||
if ("org.lwjgl.glfw.GLFW".equals(cls) && "glfwWaitEventsTimeout".equals(method)) {
|
||||
hasWait = true;
|
||||
}
|
||||
if ("com.mojang.blaze3d.systems.RenderSystem".equals(cls) && "limitDisplayFPS".equals(method)) {
|
||||
hasLimit = true;
|
||||
}
|
||||
if (hasWait || hasLimit) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String formatElement(StackTraceElement e) {
|
||||
String file = e.getFileName() == null ? "Unknown" : e.getFileName();
|
||||
int line = e.getLineNumber();
|
||||
return e.getClassName() + "." + e.getMethodName() + "(" + file + ":" + line + ")";
|
||||
}
|
||||
|
||||
private static boolean matchesTarget(Target source) {
|
||||
if (source == null) return true;
|
||||
Target target = getTargetRaw();
|
||||
return target == Target.ALL || target == source;
|
||||
}
|
||||
|
||||
private static Target getTargetRaw() {
|
||||
ProfilerSettings.SampleTarget target = ProfilerSettings.getSampleTarget();
|
||||
if (target == null) return Target.ALL;
|
||||
return switch (target) {
|
||||
case D2 -> Target.UI;
|
||||
case D3 -> Target.WORLD;
|
||||
case ALL -> Target.ALL;
|
||||
};
|
||||
}
|
||||
|
||||
private static void trimToLimit() {
|
||||
if (COUNTS.size() <= MAX_ENTRIES) return;
|
||||
List<Map.Entry<String, Integer>> entries = new ArrayList<>(COUNTS.entrySet());
|
||||
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
|
||||
for (int i = MAX_ENTRIES; i < entries.size(); i++) {
|
||||
COUNTS.remove(entries.get(i).getKey());
|
||||
}
|
||||
}
|
||||
|
||||
private static ProfilerSettings.OutputMode getOutputModeRaw() {
|
||||
return ProfilerSettings.getSampleOutput();
|
||||
}
|
||||
|
||||
private static void sleepMs(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException ignored) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
public enum Target {
|
||||
ALL,
|
||||
UI,
|
||||
WORLD
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,150 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import com.mojang.jtracy.GpuApi;
|
||||
import com.mojang.jtracy.GpuContext;
|
||||
import com.mojang.jtracy.TracyClient;
|
||||
import org.lwjgl.opengl.GL;
|
||||
import org.lwjgl.opengl.GL15C;
|
||||
import org.lwjgl.opengl.GL33C;
|
||||
import org.lwjgl.opengl.GLCapabilities;
|
||||
import dev.loki.lovisual.render.engine.guard.LegacyRenderPath;
|
||||
import dev.loki.lovisual.render.engine.guard.RenderBoundaryExempt;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
|
||||
@RenderBoundaryExempt(value = LegacyRenderPath.DIRECT_GL_OUTSIDE_BACKEND, reason = "Profiler-only timer query path; not part of renderer submission architecture")
|
||||
public enum DevTracyGpuProfiler {
|
||||
;
|
||||
|
||||
private static final Scope NOOP_SCOPE = new Scope(false);
|
||||
private static final Object LOCK = new Object();
|
||||
private static final ArrayDeque<QueryEvent> PENDING = new ArrayDeque<>();
|
||||
private static final ArrayDeque<Integer> FREE_GL_QUERIES = new ArrayDeque<>();
|
||||
|
||||
private static volatile boolean initAttempted;
|
||||
private static volatile boolean available;
|
||||
private static volatile GpuContext context;
|
||||
private static int nextQueryId = 1;
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return DevTracyProfiler.isEnabled() && isAvailable();
|
||||
}
|
||||
|
||||
public static Scope beginZone(String name) {
|
||||
if (!isEnabled() || name == null || name.isBlank()) {
|
||||
return NOOP_SCOPE;
|
||||
}
|
||||
int beginId = allocateQueryId();
|
||||
int beginQuery = allocateGlQuery();
|
||||
context.beginZone(beginId, name, "", "", 0);
|
||||
GL33C.glQueryCounter(beginQuery, GL33C.GL_TIMESTAMP);
|
||||
enqueue(beginId, beginQuery);
|
||||
return new Scope(true);
|
||||
}
|
||||
|
||||
public static void onFrameEnd() {
|
||||
if (!isEnabled()) {
|
||||
return;
|
||||
}
|
||||
pump();
|
||||
}
|
||||
|
||||
private static boolean isAvailable() {
|
||||
ensureContext();
|
||||
return available;
|
||||
}
|
||||
|
||||
private static void ensureContext() {
|
||||
if (initAttempted) {
|
||||
return;
|
||||
}
|
||||
synchronized (LOCK) {
|
||||
if (initAttempted) {
|
||||
return;
|
||||
}
|
||||
initAttempted = true;
|
||||
try {
|
||||
GLCapabilities caps = GL.getCapabilities();
|
||||
boolean timerQuery = caps.OpenGL33 || caps.GL_ARB_timer_query;
|
||||
if (!timerQuery) {
|
||||
available = false;
|
||||
ProfilerLog.warn("Tracy GPU unavailable: timer queries are not supported by this OpenGL context");
|
||||
return;
|
||||
}
|
||||
long gpuTimestamp = GL33C.glGetInteger64(GL33C.GL_TIMESTAMP);
|
||||
context = TracyClient.createGpuContext(GpuApi.OPENGL, gpuTimestamp, 1.0f);
|
||||
context.setName("main");
|
||||
available = true;
|
||||
ProfilerLog.info("Tracy GPU context initialized");
|
||||
} catch (Throwable t) {
|
||||
available = false;
|
||||
ProfilerLog.warn("Tracy GPU unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void pump() {
|
||||
synchronized (LOCK) {
|
||||
while (!PENDING.isEmpty()) {
|
||||
QueryEvent event = PENDING.peekFirst();
|
||||
if (GL15C.glGetQueryObjecti(event.glQuery, GL15C.GL_QUERY_RESULT_AVAILABLE) == 0) {
|
||||
break;
|
||||
}
|
||||
long timestamp = GL33C.glGetQueryObjecti64(event.glQuery, GL15C.GL_QUERY_RESULT);
|
||||
context.submitQueryTimestamp(event.queryId, timestamp);
|
||||
PENDING.removeFirst();
|
||||
FREE_GL_QUERIES.addLast(event.glQuery);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void enqueue(int queryId, int glQuery) {
|
||||
synchronized (LOCK) {
|
||||
PENDING.addLast(new QueryEvent(queryId, glQuery));
|
||||
}
|
||||
}
|
||||
|
||||
private static int allocateQueryId() {
|
||||
synchronized (LOCK) {
|
||||
int id = nextQueryId++;
|
||||
if (id <= 0) {
|
||||
nextQueryId = 1;
|
||||
id = nextQueryId++;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
private static int allocateGlQuery() {
|
||||
synchronized (LOCK) {
|
||||
Integer existing = FREE_GL_QUERIES.pollFirst();
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
return GL15C.glGenQueries();
|
||||
}
|
||||
|
||||
private record QueryEvent(int queryId, int glQuery) {
|
||||
}
|
||||
|
||||
public static final class Scope implements AutoCloseable {
|
||||
private final boolean active;
|
||||
|
||||
private Scope(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!active || !isEnabled()) {
|
||||
return;
|
||||
}
|
||||
int endId = allocateQueryId();
|
||||
int endQuery = allocateGlQuery();
|
||||
context.endZone(endId);
|
||||
GL33C.glQueryCounter(endQuery, GL33C.GL_TIMESTAMP);
|
||||
enqueue(endId, endQuery);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,230 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import com.mojang.jtracy.Plot;
|
||||
import com.mojang.jtracy.TracyClient;
|
||||
import com.mojang.jtracy.Zone;
|
||||
|
||||
public enum DevTracyProfiler {
|
||||
;
|
||||
|
||||
private static final Scope NOOP_SCOPE = new Scope(null);
|
||||
private static final ThreadLocal<Boolean> THREAD_NAMED =
|
||||
ThreadLocal.withInitial(() -> Boolean.FALSE);
|
||||
|
||||
private static volatile boolean loadAttempted;
|
||||
private static volatile boolean available;
|
||||
private static volatile Plot uiFrameMsPlot;
|
||||
private static volatile Plot uiNodeCountPlot;
|
||||
private static volatile Plot worldFrameMsPlot;
|
||||
private static volatile Plot worldNodeCountPlot;
|
||||
private static volatile Plot glWaitMsPlot;
|
||||
private static volatile Plot glWaitCallsPlot;
|
||||
private static volatile Plot uiBatchDrawsPlot;
|
||||
private static volatile Plot uiBatchVerticesPlot;
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return ProfilerSettings.isTracyEnabled() && isAvailable();
|
||||
}
|
||||
|
||||
public static boolean isAvailable() {
|
||||
ensureLoaded();
|
||||
return available;
|
||||
}
|
||||
|
||||
public static synchronized boolean setEnabled(boolean enabled) {
|
||||
ProfilerSettings.setTracyEnabled(enabled);
|
||||
if (!enabled) {
|
||||
ProfilerLog.info("Tracy disabled");
|
||||
return false;
|
||||
}
|
||||
boolean active = isAvailable();
|
||||
if (active) {
|
||||
ProfilerLog.info("Tracy enabled; data is streamed to the external Tracy viewer, not latest.log");
|
||||
TracyClient.message("LoVisual Tracy enabled");
|
||||
}
|
||||
return active;
|
||||
}
|
||||
|
||||
public static Scope beginZone(String name) {
|
||||
if (!isEnabled() || name == null || name.isBlank()) {
|
||||
return NOOP_SCOPE;
|
||||
}
|
||||
ensureThreadNamed();
|
||||
return new Scope(TracyClient.beginZone(name, false));
|
||||
}
|
||||
|
||||
public static void markFrame() {
|
||||
if (!isEnabled()) return;
|
||||
ensureThreadNamed();
|
||||
TracyClient.markFrame();
|
||||
}
|
||||
|
||||
public static boolean shouldTraceCurrentThread() {
|
||||
String threadName = Thread.currentThread().getName();
|
||||
if (threadName == null || threadName.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
return "Render thread".equals(threadName)
|
||||
|| threadName.startsWith("Render thread")
|
||||
|| "main".equals(threadName)
|
||||
|| "Main thread".equals(threadName);
|
||||
}
|
||||
|
||||
public static void plotUiFrame(double ms, int nodes) {
|
||||
if (!isEnabled()) return;
|
||||
plotUiFrameMs().setValue(ms);
|
||||
plotUiNodeCount().setValue(nodes);
|
||||
}
|
||||
|
||||
public static void plotWorldFrame(double ms, int nodes) {
|
||||
if (!isEnabled()) return;
|
||||
plotWorldFrameMs().setValue(ms);
|
||||
plotWorldNodeCount().setValue(nodes);
|
||||
}
|
||||
|
||||
public static void plotGlWait(double ms, int calls) {
|
||||
if (!isEnabled()) return;
|
||||
plotGlWaitMs().setValue(ms);
|
||||
plotGlWaitCalls().setValue(calls);
|
||||
}
|
||||
|
||||
public static void plotUiBatch(int draws, int vertices) {
|
||||
if (!isEnabled()) return;
|
||||
plotUiBatchDraws().setValue(draws);
|
||||
plotUiBatchVertices().setValue(vertices);
|
||||
}
|
||||
|
||||
private static void ensureLoaded() {
|
||||
if (loadAttempted) {
|
||||
return;
|
||||
}
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (loadAttempted) {
|
||||
return;
|
||||
}
|
||||
loadAttempted = true;
|
||||
try {
|
||||
TracyClient.load();
|
||||
TracyClient.reportAppInfo("LoVisual render profiler");
|
||||
available = TracyClient.isAvailable();
|
||||
if (available) {
|
||||
ProfilerLog.info("Tracy client loaded");
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
available = false;
|
||||
ProfilerLog.warn("Tracy unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ensureThreadNamed() {
|
||||
if (Boolean.TRUE.equals(THREAD_NAMED.get())) {
|
||||
return;
|
||||
}
|
||||
TracyClient.setThreadName(Thread.currentThread().getName(), 0);
|
||||
THREAD_NAMED.set(Boolean.TRUE);
|
||||
}
|
||||
|
||||
private static Plot plotUiFrameMs() {
|
||||
Plot plot = uiFrameMsPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (uiFrameMsPlot == null) {
|
||||
uiFrameMsPlot = TracyClient.createPlot("render.ui.ms");
|
||||
}
|
||||
return uiFrameMsPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotUiNodeCount() {
|
||||
Plot plot = uiNodeCountPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (uiNodeCountPlot == null) {
|
||||
uiNodeCountPlot = TracyClient.createPlot("render.ui.nodes");
|
||||
}
|
||||
return uiNodeCountPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotWorldFrameMs() {
|
||||
Plot plot = worldFrameMsPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (worldFrameMsPlot == null) {
|
||||
worldFrameMsPlot = TracyClient.createPlot("render.world.ms");
|
||||
}
|
||||
return worldFrameMsPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotWorldNodeCount() {
|
||||
Plot plot = worldNodeCountPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (worldNodeCountPlot == null) {
|
||||
worldNodeCountPlot = TracyClient.createPlot("render.world.nodes");
|
||||
}
|
||||
return worldNodeCountPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotGlWaitMs() {
|
||||
Plot plot = glWaitMsPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (glWaitMsPlot == null) {
|
||||
glWaitMsPlot = TracyClient.createPlot("render.gl_wait.ms");
|
||||
}
|
||||
return glWaitMsPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotGlWaitCalls() {
|
||||
Plot plot = glWaitCallsPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (glWaitCallsPlot == null) {
|
||||
glWaitCallsPlot = TracyClient.createPlot("render.gl_wait.calls");
|
||||
}
|
||||
return glWaitCallsPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotUiBatchDraws() {
|
||||
Plot plot = uiBatchDrawsPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (uiBatchDrawsPlot == null) {
|
||||
uiBatchDrawsPlot = TracyClient.createPlot("render.ui_batch.draws");
|
||||
}
|
||||
return uiBatchDrawsPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotUiBatchVertices() {
|
||||
Plot plot = uiBatchVerticesPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (uiBatchVerticesPlot == null) {
|
||||
uiBatchVerticesPlot = TracyClient.createPlot("render.ui_batch.vertices");
|
||||
}
|
||||
return uiBatchVerticesPlot;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Scope implements AutoCloseable {
|
||||
private final Zone zone;
|
||||
|
||||
private Scope(Zone zone) {
|
||||
this.zone = zone;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (zone != null) {
|
||||
zone.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
16
mod/src/dev/resources/lovisual-dev.mixins.json
Normal file
16
mod/src/dev/resources/lovisual-dev.mixins.json
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"required": true,
|
||||
"plugin": "dev.loki.lovisual.mixins.LoVisualMixinPlugin",
|
||||
"minVersion": "0.8",
|
||||
"package": "dev.loki.lovisual.mixins",
|
||||
"compatibilityLevel": "JAVA_21",
|
||||
"client": [
|
||||
"ProfilersMixin"
|
||||
],
|
||||
"injectors": {
|
||||
"defaultRequire": 1
|
||||
},
|
||||
"overwrites": {
|
||||
"requireAnnotations": true
|
||||
}
|
||||
}
|
||||
60
mod/src/main/java/dev/loki/lovisual/Lifecycle.java
Normal file
60
mod/src/main/java/dev/loki/lovisual/Lifecycle.java
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual;
|
||||
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
import dev.loki.lovisual.util.resources.RenderResourceReadiness;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/**
|
||||
* Minimal client lifecycle: INIT until explicitly activated, then ACTIVE.
|
||||
* Replaces the former Runtime/JarReplacement state machine.
|
||||
*/
|
||||
public enum Lifecycle {
|
||||
;
|
||||
|
||||
private enum State {
|
||||
INIT,
|
||||
ACTIVE,
|
||||
SHUTDOWN
|
||||
}
|
||||
|
||||
private static final AtomicReference<State> STATE = new AtomicReference<>(State.INIT);
|
||||
|
||||
private Lifecycle() {
|
||||
}
|
||||
|
||||
public static void activate() {
|
||||
if (STATE.compareAndSet(State.INIT, State.ACTIVE)) {
|
||||
DebugLog.info("Lifecycle: INIT -> ACTIVE");
|
||||
}
|
||||
}
|
||||
|
||||
public static void shutdown() {
|
||||
if (STATE.getAndSet(State.SHUTDOWN) != State.SHUTDOWN) {
|
||||
DebugLog.info("Lifecycle: -> SHUTDOWN");
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isActive() {
|
||||
return STATE.get() == State.ACTIVE;
|
||||
}
|
||||
|
||||
public static boolean canRunRender() {
|
||||
return isActive() && RenderResourceReadiness.isReady();
|
||||
}
|
||||
|
||||
public static boolean canRunHud() {
|
||||
return canRunRender();
|
||||
}
|
||||
|
||||
public static boolean canRunShaderBridge() {
|
||||
return canRunRender();
|
||||
}
|
||||
}
|
||||
437
mod/src/main/java/dev/loki/lovisual/LoVisual.java
Normal file
437
mod/src/main/java/dev/loki/lovisual/LoVisual.java
Normal file
|
|
@ -0,0 +1,437 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual;
|
||||
|
||||
import dev.loki.lovisual.events.impl.render.GameTickEvent;
|
||||
import net.fabricmc.api.ClientModInitializer;
|
||||
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
|
||||
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
|
||||
import net.fabricmc.fabric.api.client.rendering.v1.hud.HudElementRegistry;
|
||||
import net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements;
|
||||
import net.fabricmc.fabric.api.client.rendering.v1.level.LevelRenderEvents;
|
||||
import net.minecraft.client.DeltaTracker;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonRenderPipelineManager;
|
||||
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
|
||||
import dev.loki.lovisual.config.i18n.MainConfig;
|
||||
import dev.loki.lovisual.events.Events;
|
||||
import dev.loki.lovisual.features.account.AccountConfig;
|
||||
import dev.loki.lovisual.features.command.core.CommandManager;
|
||||
import dev.loki.lovisual.features.gui.clickgui.render.ClickGuiRenderer;
|
||||
import dev.loki.lovisual.features.gui.clickgui.settings.i18n.I18nPreflightContributors;
|
||||
import dev.loki.lovisual.features.gui.hud.registry.HudElements;
|
||||
import dev.loki.lovisual.features.gui.hud.anchor.HudRenderSpace;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementBootstrap;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.impl.buttons.SwapTooltip;
|
||||
import dev.loki.lovisual.features.module.phase.HudPhase;
|
||||
import dev.loki.lovisual.features.module.lifecycle.ModuleAutoLoader;
|
||||
import dev.loki.lovisual.features.module.core.ModuleManager;
|
||||
import dev.loki.lovisual.features.module.phase.WorldPhase;
|
||||
import dev.loki.lovisual.mixininterface.render.IGuiGraphics;
|
||||
import dev.loki.lovisual.render.effects.NetherPortalRiftPass;
|
||||
import dev.loki.lovisual.render.effects.SleepOverlayPass;
|
||||
import dev.loki.lovisual.render.engine.LoVisualRenderEngineBootstrap;
|
||||
import dev.loki.lovisual.render.engine.core.system.LoVisualRenderSystem;
|
||||
import dev.loki.lovisual.render.engine.core.frame.RenderPhase;
|
||||
import dev.loki.lovisual.render.engine.core.frame.RenderPhaseScope;
|
||||
import dev.loki.lovisual.render.engine.core.context.ViewportContext;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessManager;
|
||||
import dev.loki.lovisual.render.engine.profiler.config.ProfilerPhase;
|
||||
import dev.loki.lovisual.render.engine.profiler.render.RenderProfiler2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.FullScreenRenderer;
|
||||
import dev.loki.lovisual.render.engine.prewarm.RenderPrewarmContributors;
|
||||
import dev.loki.lovisual.render.engine.prewarm.RenderPrewarmManager;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
import dev.loki.lovisual.render.helpers.util.SystemCursor;
|
||||
import dev.loki.lovisual.render.helpers.util.TickDelta;
|
||||
import dev.loki.lovisual.util.aiming.rotation.RotationManager;
|
||||
import dev.loki.lovisual.util.block.bed.SelfBedTracker;
|
||||
import dev.loki.lovisual.util.click.AttackPressing;
|
||||
import dev.loki.lovisual.util.combat.tracking.AntiBotTracker;
|
||||
import dev.loki.lovisual.util.combat.protocol.heuristics.CombatProtocolHeuristics;
|
||||
import dev.loki.lovisual.util.combat.rotation.SprintController;
|
||||
import dev.loki.lovisual.util.entity.simulation.BoatSimulationCache;
|
||||
import dev.loki.lovisual.util.media.session.MediaSessionService;
|
||||
import dev.loki.lovisual.util.network.control.BacktrackController;
|
||||
import dev.loki.lovisual.util.network.control.BlinkManager;
|
||||
import dev.loki.lovisual.util.proxy.ProxyBackend;
|
||||
import dev.loki.lovisual.util.network.control.FakeLagController;
|
||||
import dev.loki.lovisual.util.player.simulation.PlayerSimulationCache;
|
||||
import dev.loki.lovisual.util.pvp.tracker.PvpTargetTracker;
|
||||
import dev.loki.lovisual.util.pvp.tracker.PvpTracker;
|
||||
import dev.loki.lovisual.util.target.TargetManager;
|
||||
import dev.loki.lovisual.util.time.TimerController;
|
||||
import dev.loki.lovisual.features.gui.clickgui.settings.bind.KeyBindSetting;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
|
||||
public class LoVisual implements ClientModInitializer {
|
||||
|
||||
private static void renderWorldPhase(WorldPhase phase,
|
||||
com.mojang.blaze3d.vertex.PoseStack matrices,
|
||||
net.minecraft.client.renderer.SubmitNodeCollector consumers) {
|
||||
if (!Lifecycle.canRunRender()) return;
|
||||
|
||||
ModuleManager.renderWorld(
|
||||
phase,
|
||||
matrices,
|
||||
consumers,
|
||||
TickDelta.tickProgress(false)
|
||||
);
|
||||
}
|
||||
|
||||
private static void refreshHudFrameTiming(DeltaTracker tickCounter) {
|
||||
LoVisualRenderSystem.updateFrameTiming(
|
||||
TickDelta.tickProgress(tickCounter, false),
|
||||
TickDelta.frameDeltaTicks(tickCounter),
|
||||
TickDelta.fixedDeltaTicks(tickCounter)
|
||||
);
|
||||
}
|
||||
|
||||
private static void renderHudPhase(HudPhase phase, GuiGraphicsExtractor ctx, DeltaTracker tickCounter) {
|
||||
if (!Lifecycle.canRunHud()) return;
|
||||
float tickProgress = TickDelta.tickProgress(tickCounter, false);
|
||||
ModuleManager.renderHud(phase, ctx, tickProgress);
|
||||
Renderer2D.Deferred2DLayer layer = deferredLayerForHudPhase(phase);
|
||||
if (renderHudEngine(phase, layer, ctx, tickCounter)) {
|
||||
appendHudDeferredMarker(layer, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean renderHudEngine(HudPhase phase,
|
||||
Renderer2D.Deferred2DLayer layer,
|
||||
GuiGraphicsExtractor ctx,
|
||||
DeltaTracker tickCounter) {
|
||||
boolean rawMain = hasHudMainPassWork(phase, HudRenderSpace.UNSCALED)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_RAW);
|
||||
boolean scaledMain = hasHudMainPassWork(phase, HudRenderSpace.SCALED)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_SCALED);
|
||||
boolean logicalMain = hasHudMainPassWork(phase, HudRenderSpace.UNSCALED_LOGICAL)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_LOGICAL);
|
||||
boolean rawForeground = hasHudForegroundPassWork(phase, HudRenderSpace.UNSCALED)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_RAW_FOREGROUND);
|
||||
boolean scaledForeground = hasHudForegroundPassWork(phase, HudRenderSpace.SCALED)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_SCALED_FOREGROUND);
|
||||
boolean logicalForeground = hasHudForegroundPassWork(phase, HudRenderSpace.UNSCALED_LOGICAL)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_LOGICAL_FOREGROUND);
|
||||
if (!rawMain && !scaledMain && !logicalMain && !rawForeground && !scaledForeground && !logicalForeground) {
|
||||
return false;
|
||||
}
|
||||
|
||||
float tickProgress = TickDelta.tickProgress(tickCounter, false);
|
||||
TextRenderer textRenderer = TextRenderer.get();
|
||||
|
||||
FullScreenRenderer.ensureInit();
|
||||
ViewportContext.beginUnscaled(ctx);
|
||||
refreshHudFrameTiming(tickCounter);
|
||||
|
||||
Renderer2D.withDeferredLayer(layer, () -> {
|
||||
SystemCursor.beginFrame(ctx);
|
||||
try (RenderPhaseScope hudPhase = LoVisualRenderSystem.phase(RenderPhase.HUD_MAIN, "2d:phase:" + phase.name())) {
|
||||
// Raw HUD pass
|
||||
if (rawMain) {
|
||||
Renderer2D.COLOR.begin();
|
||||
ModuleManager.renderHudEngine(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
StaticHudElementRegistry.renderAllEngine(phase, HudRenderSpace.UNSCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_RAW, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
|
||||
// Scaled fixed HUD pass
|
||||
if (scaledMain) {
|
||||
ViewportContext.beginScaled(ctx);
|
||||
Renderer2D.COLOR.begin();
|
||||
StaticHudElementRegistry.renderAllEngine(phase, HudRenderSpace.SCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_SCALED, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
|
||||
// Logical HUD pass
|
||||
if (logicalMain) {
|
||||
ViewportContext.beginUnscaledLogical(ctx);
|
||||
Renderer2D.COLOR.begin();
|
||||
StaticHudElementRegistry.renderAllEngine(phase, HudRenderSpace.UNSCALED_LOGICAL, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
DraggableHudElementRegistry.renderAllEngine(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_LOGICAL, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
|
||||
// Raw foreground
|
||||
if (rawForeground) {
|
||||
ViewportContext.beginUnscaled(ctx);
|
||||
Renderer2D.COLOR.begin();
|
||||
ModuleManager.renderHudEngineForeground(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
StaticHudElementRegistry.renderAllEngineForeground(phase, HudRenderSpace.UNSCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_RAW_FOREGROUND, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
|
||||
// Scaled fixed HUD foreground
|
||||
if (scaledForeground) {
|
||||
ViewportContext.beginScaled(ctx);
|
||||
Renderer2D.COLOR.begin();
|
||||
StaticHudElementRegistry.renderAllEngineForeground(phase, HudRenderSpace.SCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_SCALED_FOREGROUND, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
|
||||
// Logical foreground
|
||||
if (logicalForeground) {
|
||||
ViewportContext.beginUnscaledLogical(ctx);
|
||||
Renderer2D.COLOR.begin();
|
||||
StaticHudElementRegistry.renderAllEngineForeground(phase, HudRenderSpace.UNSCALED_LOGICAL, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
DraggableHudElementRegistry.renderAllEngineForeground(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_LOGICAL_FOREGROUND, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
} finally {
|
||||
SystemCursor.endFrame();
|
||||
ViewportContext.end(ctx);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void renderHudAfterHotbar(GuiGraphicsExtractor ctx, DeltaTracker tickCounter) {
|
||||
if (!Lifecycle.canRunHud()) return;
|
||||
boolean swapTooltipWork = SwapTooltip.hasWork();
|
||||
boolean targetHudWork = DraggableHudElementRegistry.hasEngineWidgetWork("target_hud");
|
||||
if (!swapTooltipWork && !targetHudWork) return;
|
||||
|
||||
float tickProgress = TickDelta.tickProgress(tickCounter, false);
|
||||
TextRenderer textRenderer = TextRenderer.get();
|
||||
Renderer2D.Deferred2DLayer layer = Renderer2D.Deferred2DLayer.HUD_AFTER_MISC_OVERLAYS;
|
||||
|
||||
FullScreenRenderer.ensureInit();
|
||||
ViewportContext.beginUnscaled(ctx);
|
||||
refreshHudFrameTiming(tickCounter);
|
||||
|
||||
Renderer2D.withDeferredLayer(layer, () -> {
|
||||
SystemCursor.beginFrame(ctx);
|
||||
try (RenderPhaseScope hudPhase = LoVisualRenderSystem.phase(RenderPhase.HUD_EFFECTS, "2d:after_hotbar")) {
|
||||
// Raw pass
|
||||
if (swapTooltipWork) {
|
||||
try (ProfilerPhase.Scope tooltipsScope = ProfilerPhase.scope("2d:after_hotbar:swap_tooltip");
|
||||
RenderProfiler2D.Section ignoredTooltips = RenderProfiler2D.section("swap_tooltip")) {
|
||||
Renderer2D.COLOR.begin();
|
||||
SwapTooltip.render();
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
}
|
||||
|
||||
// Logical pass
|
||||
if (targetHudWork) {
|
||||
ViewportContext.beginUnscaledLogical(ctx);
|
||||
try (ProfilerPhase.Scope targetHudScope = ProfilerPhase.scope("2d:after_hotbar:target_hud");
|
||||
RenderProfiler2D.Section ignoredTargetHud = RenderProfiler2D.section("target_hud")) {
|
||||
Renderer2D.COLOR.begin();
|
||||
DraggableHudElementRegistry.renderEngineWidget(
|
||||
"target_hud",
|
||||
Renderer2D.COLOR,
|
||||
textRenderer,
|
||||
ctx,
|
||||
tickProgress
|
||||
);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
SystemCursor.endFrame();
|
||||
ViewportContext.end(ctx);
|
||||
}
|
||||
});
|
||||
appendHudDeferredMarker(layer, ctx);
|
||||
}
|
||||
|
||||
private static void appendHudDeferredMarker(Renderer2D.Deferred2DLayer layer, GuiGraphicsExtractor ctx) {
|
||||
if (!(ctx instanceof IGuiGraphics graphics)) return;
|
||||
ctx.nextStratum();
|
||||
graphics.lovisual$addDeferredHudMarker(layer);
|
||||
ctx.nextStratum();
|
||||
}
|
||||
|
||||
private static Renderer2D.Deferred2DLayer deferredLayerForHudPhase(HudPhase phase) {
|
||||
if (phase == null) return Renderer2D.Deferred2DLayer.BEFORE_VANILLA_GUI;
|
||||
return switch (phase) {
|
||||
case NONE -> Renderer2D.Deferred2DLayer.BEFORE_VANILLA_GUI;
|
||||
case FIRST -> Renderer2D.Deferred2DLayer.HUD_FIRST;
|
||||
case BEFORE_MISC_OVERLAYS -> Renderer2D.Deferred2DLayer.HUD_BEFORE_MISC_OVERLAYS;
|
||||
case AFTER_MISC_OVERLAYS -> Renderer2D.Deferred2DLayer.HUD_AFTER_MISC_OVERLAYS;
|
||||
case AFTER_BOSS_BAR -> Renderer2D.Deferred2DLayer.HUD_AFTER_BOSS_BAR;
|
||||
case BEFORE_DEMO_TIMER -> Renderer2D.Deferred2DLayer.HUD_BEFORE_DEMO_TIMER;
|
||||
case BEFORE_CHAT -> Renderer2D.Deferred2DLayer.HUD_BEFORE_CHAT;
|
||||
case AFTER_SUBTITLES -> Renderer2D.Deferred2DLayer.HUD_AFTER_SUBTITLES;
|
||||
case LAST -> Renderer2D.Deferred2DLayer.HUD_LAST;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean hasHudMainPassWork(HudPhase phase, HudRenderSpace space) {
|
||||
boolean moduleWork = space == HudRenderSpace.UNSCALED && ModuleManager.hasHudEngineWork(phase);
|
||||
boolean staticWork = StaticHudElementRegistry.hasEngineWork(phase, space, false);
|
||||
boolean draggableWork = space == HudRenderSpace.UNSCALED_LOGICAL && DraggableHudElementRegistry.hasEngineWork(phase, false);
|
||||
return moduleWork || staticWork || draggableWork;
|
||||
}
|
||||
|
||||
private static boolean hasHudForegroundPassWork(HudPhase phase, HudRenderSpace space) {
|
||||
boolean moduleWork = space == HudRenderSpace.UNSCALED && ModuleManager.hasHudEngineForegroundWork(phase);
|
||||
boolean staticWork = StaticHudElementRegistry.hasEngineWork(phase, space, true);
|
||||
boolean draggableWork = space == HudRenderSpace.UNSCALED_LOGICAL && DraggableHudElementRegistry.hasEngineWork(phase, true);
|
||||
return moduleWork || staticWork || draggableWork;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInitializeClient() {
|
||||
LoVisualRenderEngineBootstrap.init();
|
||||
PostProcessManager.register(new NetherPortalRiftPass());
|
||||
PostProcessManager.register(new SleepOverlayPass());
|
||||
MainConfig.get(); // Load global settings (debug flag)
|
||||
AccountConfig.get();
|
||||
ProxyBackend.init();
|
||||
CommandManager.init();
|
||||
MediaSessionService.get().init();
|
||||
ClientLifecycleEvents.CLIENT_STOPPING.register(client -> MediaSessionService.get().shutdown());
|
||||
|
||||
// -------- CONFIG + BINDS ----------
|
||||
// Enabled addons declare built-in module exclusions before auto-discovery.
|
||||
AddonManager.prepareModuleLoading();
|
||||
ModuleAutoLoader.load("dev.loki.lovisual.features.module.modules");
|
||||
AddonManager.init();
|
||||
// Initialize modules' enabled state and settings from new config system
|
||||
ModuleManager.loadAllModuleConfigs();
|
||||
AddonManager.notifyClientReady();
|
||||
// Key binds are restored via Module config (KeyBindSetting) in ModuleManager.loadAllModuleConfigs()
|
||||
HudElements.init(); // init HUD config + widgets
|
||||
StaticHudElementBootstrap.init(); // init vanilla HUD elements config
|
||||
Events.BUS.register(I18nPreflightContributors.INSTANCE);
|
||||
Events.BUS.register(RenderPrewarmContributors.INSTANCE);
|
||||
Events.BUS.register(RotationManager.INSTANCE);
|
||||
Events.BUS.register(AttackPressing.INSTANCE);
|
||||
Events.BUS.register(SprintController.INSTANCE);
|
||||
Events.BUS.register(AntiBotTracker.INSTANCE);
|
||||
Events.BUS.register(CombatProtocolHeuristics.INSTANCE);
|
||||
Events.BUS.register(PvpTracker.INSTANCE);
|
||||
Events.BUS.register(PvpTargetTracker.INSTANCE);
|
||||
Events.BUS.register(SelfBedTracker.INSTANCE);
|
||||
Events.BUS.register(BoatSimulationCache.INSTANCE);
|
||||
Events.BUS.register(PlayerSimulationCache.INSTANCE);
|
||||
Events.BUS.register(BlinkManager.INSTANCE);
|
||||
Events.BUS.register(FakeLagController.INSTANCE);
|
||||
Events.BUS.register(BacktrackController.INSTANCE);
|
||||
Events.BUS.register(TimerController.INSTANCE);
|
||||
|
||||
// -------- КЛЮЧЕВЫЕ ИВЕНТЫ --------
|
||||
|
||||
// === ТИКИ ===
|
||||
|
||||
ClientTickEvents.START_CLIENT_TICK.register(client -> {
|
||||
if (client.player == null) return;
|
||||
if (!Lifecycle.isActive()) return;
|
||||
Events.BUS.post(new GameTickEvent());
|
||||
});
|
||||
|
||||
ClientTickEvents.END_CLIENT_TICK.register(client -> {
|
||||
if (!Lifecycle.isActive()) return;
|
||||
|
||||
if (!ClickGuiRenderer.isBlockingModuleKeybinds()) {
|
||||
ModuleManager.handleModuleKeybinds();
|
||||
}
|
||||
TargetManager.tick();
|
||||
ModuleManager.tickAll();
|
||||
DraggableHudElementRegistry.tickAll();
|
||||
StaticHudElementRegistry.tickAll();
|
||||
});
|
||||
|
||||
/* ====================== WORLD RENDER ====================== */
|
||||
|
||||
LevelRenderEvents.COLLECT_SUBMITS.register(ctx -> renderWorldPhase(
|
||||
WorldPhase.BEFORE_ENTITIES,
|
||||
ctx.poseStack(),
|
||||
ctx.submitNodeCollector()
|
||||
));
|
||||
|
||||
LevelRenderEvents.AFTER_SOLID_FEATURES.register(ctx -> renderWorldPhase(
|
||||
WorldPhase.AFTER_ENTITIES,
|
||||
ctx.poseStack(),
|
||||
ctx.submitNodeCollector()
|
||||
));
|
||||
|
||||
LevelRenderEvents.BEFORE_TRANSLUCENT_TERRAIN.register(ctx -> renderWorldPhase(
|
||||
WorldPhase.BEFORE_TRANSLUCENT,
|
||||
ctx.poseStack(),
|
||||
ctx.submitNodeCollector()
|
||||
));
|
||||
|
||||
LevelRenderEvents.END_MAIN.register(ctx -> renderWorldPhase(
|
||||
WorldPhase.END_MAIN,
|
||||
ctx.poseStack(),
|
||||
ctx.submitNodeCollector()
|
||||
));
|
||||
|
||||
// === HUD 2D OVERLAYS ===
|
||||
|
||||
HudElementRegistry.addFirst(
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_first"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.FIRST, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.addLast(
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_last"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.LAST, ctx, tc)
|
||||
);
|
||||
|
||||
// остальные позиции HUD:
|
||||
HudElementRegistry.attachElementBefore(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.MISC_OVERLAYS,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_before_misc"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.BEFORE_MISC_OVERLAYS, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementAfter(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.MISC_OVERLAYS,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_after_misc"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.AFTER_MISC_OVERLAYS, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementAfter(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.SLEEP,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_after_boss"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.AFTER_BOSS_BAR, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementBefore(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.DEMO_TIMER,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_before_demo"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.BEFORE_DEMO_TIMER, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementBefore(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.CHAT,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_before_chat"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.BEFORE_CHAT, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementAfter(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.SUBTITLES,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_after_subtitles"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.AFTER_SUBTITLES, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementAfter(
|
||||
VanillaHudElements.HOTBAR,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_after_hotbar"),
|
||||
(ctx, tc) -> renderHudAfterHotbar(ctx, tc)
|
||||
);
|
||||
|
||||
Lifecycle.activate();
|
||||
RenderPrewarmManager.prewarm("client initialized");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,214 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.context;
|
||||
|
||||
import dev.loki.lovisual.api.v0.addon.LoVisualAddonContext;
|
||||
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
|
||||
import dev.loki.lovisual.api.v0.client.LoVisualClientApi;
|
||||
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualPostProcessCallback;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualRenderCallback;
|
||||
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
|
||||
import com.mojang.blaze3d.pipeline.RenderPipeline;
|
||||
import dev.loki.lovisual.features.command.util.ClientCommand;
|
||||
import dev.loki.lovisual.features.command.core.CommandManager;
|
||||
import dev.loki.lovisual.features.gui.hud.base.AbstractHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessPass;
|
||||
import dev.loki.lovisual.render.iris.patch.ShaderPatchEngine;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.fabricmc.loader.api.ModContainer;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import dev.loki.lovisual.addon.core.AddonIssue;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
import dev.loki.lovisual.addon.core.AddonRegistration;
|
||||
import dev.loki.lovisual.addon.manager.ClickGuiSectionManager;
|
||||
import dev.loki.lovisual.addon.manager.ModuleExtensionManager;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonRenderPipelineManager;
|
||||
import dev.loki.lovisual.features.module.modules.misc.ClickGui;
|
||||
|
||||
public final class LoVisualAddonContextImpl implements LoVisualAddonContext {
|
||||
private final AddonRegistration registration;
|
||||
|
||||
public LoVisualAddonContextImpl(AddonRegistration registration) {
|
||||
|
||||
this.registration = registration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addonId() {
|
||||
return registration.descriptor.id();
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoVisualClientApi client() {
|
||||
return LoVisualClientApi.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModContainer modContainer() {
|
||||
return registration.entrypoint.getProvider();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path gameDir() {
|
||||
return FabricLoader.getInstance().getGameDir();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path configDir() {
|
||||
return FabricLoader.getInstance().getConfigDir();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path addonConfigDir() {
|
||||
return configDir().resolve("lovisual").resolve("addons").resolve(addonId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerModule(Module module) {
|
||||
if (module == null) return;
|
||||
module.postInit();
|
||||
registration.modules.add(module.name());
|
||||
AddonManager.noteModuleOwner(addonId(), module.name());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerDraggableHudElement(DraggableHudElement element) {
|
||||
if (element == null) return;
|
||||
DraggableHudElementRegistry.register(element);
|
||||
registration.draggableHudElements.add(element.getId());
|
||||
AddonManager.noteDraggableHudOwner(addonId(), element.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerStaticHudElement(AbstractHudElement element) {
|
||||
if (element == null) return;
|
||||
StaticHudElementRegistry.register(element);
|
||||
registration.staticHudElements.add(element.getId());
|
||||
AddonManager.noteStaticHudOwner(addonId(), element.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerCommand(ClientCommand command) {
|
||||
if (command == null) return;
|
||||
CommandManager.register(new AddonClientCommand(addonId(), command));
|
||||
registration.commands.add(command.metadata().id());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerClickGuiSection(String sectionId, String label, LoVisualClickGuiSection section) {
|
||||
if (ClickGuiSectionManager.register(addonId(), sectionId, label, section)) {
|
||||
registration.clickGuiSections.add(sectionId);
|
||||
} else {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "ClickGui section registration failed", sectionId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerModuleExtension(String moduleId, LoVisualModuleExtension extension) {
|
||||
if (ModuleExtensionManager.register(addonId(), moduleId, extension)) {
|
||||
registration.moduleExtensions.add(moduleId);
|
||||
} else {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Module extension target is unavailable", moduleId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerIrisShaderPatchManifest(String manifestResourcePath) {
|
||||
if (ShaderPatchEngine.registerManifestResource(manifestResourcePath)) {
|
||||
registration.irisPatchManifests.add(manifestResourcePath);
|
||||
} else {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Iris patch manifest registration failed", manifestResourcePath);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerRenderCallback(String callbackId, LoVisualRenderStage stage, LoVisualRenderCallback callback) {
|
||||
if (AddonRenderPipelineManager.register(addonId(), callbackId, stage, callback)) {
|
||||
registration.renderCallbacks.add(stage.name().toLowerCase(java.util.Locale.ROOT) + ":" + callbackId);
|
||||
} else {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Render callback registration failed", callbackId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerPostProcessPass(String passId,
|
||||
PostProcessPass.Phase phase,
|
||||
int priority,
|
||||
LoVisualPostProcessCallback callback) {
|
||||
if (AddonRenderPipelineManager.registerPostProcess(addonId(), passId, phase, priority, callback)) {
|
||||
registration.postProcessPasses.add(phase.name().toLowerCase(java.util.Locale.ROOT) + ":" + passId);
|
||||
} else {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Post-process registration failed", passId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RenderPipeline registerRenderPipeline(RenderPipeline pipeline) {
|
||||
if (pipeline == null) return null;
|
||||
RenderPipeline registered = LoVisualRenderPipelines.registerAddonPipeline(pipeline);
|
||||
registration.renderCallbacks.add("pipeline:" + pipeline.getLocation());
|
||||
return registered;
|
||||
}
|
||||
|
||||
private record AddonClientCommand(String addonId, ClientCommand delegate) implements ClientCommand {
|
||||
@Override
|
||||
public dev.loki.lovisual.features.command.core.CommandMetadata metadata() {
|
||||
return delegate.metadata();
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
@Override
|
||||
@SuppressWarnings("removal")
|
||||
public String name() {
|
||||
return delegate.name();
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
@Override
|
||||
@SuppressWarnings("removal")
|
||||
public java.util.List<String> aliases() {
|
||||
return delegate.aliases();
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
@Override
|
||||
@SuppressWarnings("removal")
|
||||
public String usage() {
|
||||
return delegate.usage();
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
@Override
|
||||
@SuppressWarnings("removal")
|
||||
public String description() {
|
||||
return delegate.description();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable() {
|
||||
return AddonManager.isActive(addonId) && delegate.isAvailable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.List<String> suggest(dev.loki.lovisual.features.command.core.CommandContext ctx, int argIndex, String token) {
|
||||
return delegate.suggest(ctx, argIndex, token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean execute(dev.loki.lovisual.features.command.core.CommandContext ctx) {
|
||||
return isAvailable() && delegate.execute(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.context;
|
||||
|
||||
import dev.loki.lovisual.api.v0.addon.LoVisualAddonRuntimeContext;
|
||||
import dev.loki.lovisual.api.v0.client.LoVisualClientApi;
|
||||
|
||||
public final class LoVisualAddonRuntimeContextImpl implements LoVisualAddonRuntimeContext {
|
||||
private final String addonId;
|
||||
|
||||
public LoVisualAddonRuntimeContextImpl(String addonId) {
|
||||
|
||||
this.addonId = addonId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addonId() {
|
||||
return addonId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoVisualClientApi client() {
|
||||
return LoVisualClientApi.get();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.context;
|
||||
|
||||
import dev.loki.lovisual.api.v0.addon.LoVisualModuleLoadContext;
|
||||
import dev.loki.lovisual.features.module.lifecycle.ModuleAutoLoader;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import dev.loki.lovisual.addon.core.AddonIssue;
|
||||
import dev.loki.lovisual.addon.core.AddonRegistration;
|
||||
|
||||
public final class LoVisualModuleLoadContextImpl implements LoVisualModuleLoadContext {
|
||||
private final AddonRegistration registration;
|
||||
private final List<String> pendingExclusions = new ArrayList<>();
|
||||
|
||||
public LoVisualModuleLoadContextImpl(AddonRegistration registration) {
|
||||
|
||||
this.registration = registration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addonId() {
|
||||
return registration.descriptor.id();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean disableBuiltInModule(String moduleReference) {
|
||||
String reference = moduleReference == null ? "" : moduleReference.trim();
|
||||
if (reference.isEmpty()) return false;
|
||||
|
||||
if (!ModuleAutoLoader.acceptsDisableRequests()) {
|
||||
noteRestartRequired(reference);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!pendingExclusions.contains(reference)) {
|
||||
pendingExclusions.add(reference);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void commit() {
|
||||
|
||||
for (String reference : pendingExclusions) {
|
||||
if (!registration.disabledBuiltInModules.contains(reference)) {
|
||||
registration.disabledBuiltInModules.add(reference);
|
||||
}
|
||||
if (!ModuleAutoLoader.requestDisable(reference, addonId())) {
|
||||
noteRestartRequired(reference);
|
||||
}
|
||||
}
|
||||
pendingExclusions.clear();
|
||||
}
|
||||
|
||||
private void noteRestartRequired(String reference) {
|
||||
if (!registration.disabledBuiltInModules.contains(reference)) {
|
||||
registration.disabledBuiltInModules.add(reference);
|
||||
}
|
||||
registration.restartRequired = true;
|
||||
registration.issue(
|
||||
AddonIssue.Severity.WARNING,
|
||||
"Built-in module exclusion requires restart",
|
||||
reference
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.context;
|
||||
|
||||
import dev.loki.lovisual.api.v0.module.ModuleExtensionContext;
|
||||
import dev.loki.lovisual.config.definition.SettingDef;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.config.values.mode.ModeValue;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
|
||||
public final class ModuleExtensionContextImpl implements ModuleExtensionContext {
|
||||
private final String addonId;
|
||||
private final Module module;
|
||||
|
||||
public ModuleExtensionContextImpl(String addonId, Module module) {
|
||||
|
||||
this.addonId = addonId;
|
||||
this.module = module;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addonId() {
|
||||
return addonId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String moduleId() {
|
||||
return module.name();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Module module() {
|
||||
return module;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSetting(SettingDef setting) {
|
||||
module.addExtensionSetting(setting);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValue<?> getConfigValue(String configName) {
|
||||
return module.getConfigValue(configName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addModeOption(String configName, String option) {
|
||||
ConfigValue<?> value = getConfigValue(configName);
|
||||
return value instanceof ModeValue mode && mode.addOption(option);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.core;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AddonDescriptor(
|
||||
String id,
|
||||
String name,
|
||||
String version,
|
||||
String description,
|
||||
List<String> authors,
|
||||
String iconPath,
|
||||
int apiVersion,
|
||||
String entrypointDefinition
|
||||
) {
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.core;
|
||||
|
||||
public record AddonIssue(
|
||||
String addonId,
|
||||
Severity severity,
|
||||
String message,
|
||||
String detail
|
||||
) {
|
||||
public enum Severity {
|
||||
INFO,
|
||||
WARNING,
|
||||
ERROR
|
||||
}
|
||||
}
|
||||
486
mod/src/main/java/dev/loki/lovisual/addon/core/AddonManager.java
Normal file
486
mod/src/main/java/dev/loki/lovisual/addon/core/AddonManager.java
Normal file
|
|
@ -0,0 +1,486 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.core;
|
||||
|
||||
import dev.loki.lovisual.api.v0.addon.LoVisualAddon;
|
||||
import dev.loki.lovisual.features.gui.hud.base.AbstractHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.lifecycle.ModuleAutoLoader;
|
||||
import dev.loki.lovisual.features.module.core.ModuleManager;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.fabricmc.loader.api.metadata.CustomValue;
|
||||
import net.fabricmc.loader.api.metadata.ModMetadata;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.addon.context.LoVisualAddonContextImpl;
|
||||
import dev.loki.lovisual.addon.context.LoVisualAddonRuntimeContextImpl;
|
||||
import dev.loki.lovisual.addon.context.LoVisualModuleLoadContextImpl;
|
||||
import dev.loki.lovisual.addon.core.AddonDescriptor;
|
||||
import dev.loki.lovisual.addon.core.AddonIssue;
|
||||
import dev.loki.lovisual.addon.core.AddonRegistration;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonSnapshot;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonStateStore;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonStatus;
|
||||
|
||||
public enum AddonManager {
|
||||
;
|
||||
|
||||
public static final String ADDON_METADATA_KEY = "lovisual:addon";
|
||||
|
||||
private static final Map<String, AddonRegistration> ADDONS = new LinkedHashMap<>();
|
||||
private static final Map<String, Boolean> ENABLED_OVERRIDES = new LinkedHashMap<>();
|
||||
private static final Map<String, String> MODULE_OWNERS = new LinkedHashMap<>();
|
||||
private static final Map<String, String> DRAGGABLE_HUD_OWNERS = new LinkedHashMap<>();
|
||||
private static final Map<String, String> STATIC_HUD_OWNERS = new LinkedHashMap<>();
|
||||
private static boolean discovered;
|
||||
private static boolean moduleLoadingPrepared;
|
||||
private static boolean initialized;
|
||||
private static boolean clientReady;
|
||||
|
||||
/**
|
||||
* Discovers enabled addon entrypoints and lets them configure built-in module
|
||||
* exclusions before {@code ModuleAutoLoader} starts instantiating modules.
|
||||
*/
|
||||
public static void prepareModuleLoading() {
|
||||
ensureDiscovered();
|
||||
if (moduleLoadingPrepared) return;
|
||||
moduleLoadingPrepared = true;
|
||||
configureEnabledAddons();
|
||||
}
|
||||
|
||||
public static void init() {
|
||||
if (initialized) return;
|
||||
prepareModuleLoading();
|
||||
if (!ModuleAutoLoader.isDiscoveryFinished()) {
|
||||
return;
|
||||
}
|
||||
reconcileModuleExclusions();
|
||||
initialized = true;
|
||||
initializeEnabledAddons();
|
||||
}
|
||||
|
||||
/**
|
||||
* Completes addon startup after module configs have been loaded and applied.
|
||||
*/
|
||||
public static void notifyClientReady() {
|
||||
init();
|
||||
if (!initialized) return;
|
||||
clientReady = true;
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
notifyClientReady(registration);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ensureDiscovered() {
|
||||
if (discovered) return;
|
||||
discovered = true;
|
||||
ENABLED_OVERRIDES.clear();
|
||||
ENABLED_OVERRIDES.putAll(AddonStateStore.loadEnabledOverrides());
|
||||
discoverEntrypoints();
|
||||
}
|
||||
|
||||
public static List<AddonSnapshot> snapshots() {
|
||||
init();
|
||||
return ADDONS.values().stream()
|
||||
.map(AddonRegistration::snapshot)
|
||||
.sorted(Comparator.comparing(AddonSnapshot::name, String.CASE_INSENSITIVE_ORDER))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public static AddonSnapshot snapshot(String id) {
|
||||
init();
|
||||
AddonRegistration registration = ADDONS.get(normalizeId(id));
|
||||
return registration == null ? null : registration.snapshot();
|
||||
}
|
||||
|
||||
public static boolean isActive(String id) {
|
||||
init();
|
||||
AddonRegistration registration = ADDONS.get(normalizeId(id));
|
||||
return registration != null && registration.enabled && registration.status == AddonStatus.ACTIVE;
|
||||
}
|
||||
|
||||
public static List<AddonIssue> scan() {
|
||||
init();
|
||||
List<AddonIssue> out = new ArrayList<>();
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
validateRegistration(registration);
|
||||
out.addAll(registration.issues);
|
||||
}
|
||||
if (out.isEmpty()) {
|
||||
out.add(new AddonIssue("lovisual", AddonIssue.Severity.INFO, "No addon errors found", ""));
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
public static String moduleProfileOwnerId(String moduleId) {
|
||||
String addonId = MODULE_OWNERS.get(normalizeId(moduleId));
|
||||
return addonId == null ? "module:" + moduleId : "addon:" + addonId + ":module:" + moduleId;
|
||||
}
|
||||
|
||||
public static String draggableHudProfileOwnerId(String elementId) {
|
||||
String addonId = DRAGGABLE_HUD_OWNERS.get(normalizeId(elementId));
|
||||
return addonId == null ? "hud.draggable:" + elementId : "addon:" + addonId + ":hud.draggable:" + elementId;
|
||||
}
|
||||
|
||||
public static String staticHudProfileOwnerId(String elementId) {
|
||||
String addonId = STATIC_HUD_OWNERS.get(normalizeId(elementId));
|
||||
return addonId == null ? "hud.static:" + elementId : "addon:" + addonId + ":hud.static:" + elementId;
|
||||
}
|
||||
|
||||
public static String profileDisplayName(String ownerId, String displayName) {
|
||||
String addonId = addonIdFromProfileOwner(ownerId);
|
||||
if (addonId == null) return displayName;
|
||||
AddonRegistration registration = ADDONS.get(addonId);
|
||||
String addonName = registration == null ? addonId : registration.descriptor.name();
|
||||
return addonName + " / " + displayName;
|
||||
}
|
||||
|
||||
public static String addonIdFromProfileOwner(String ownerId) {
|
||||
if (ownerId == null || !ownerId.startsWith("addon:")) return null;
|
||||
int start = "addon:".length();
|
||||
int end = ownerId.indexOf(':', start);
|
||||
if (end <= start) return null;
|
||||
return normalizeId(ownerId.substring(start, end));
|
||||
}
|
||||
|
||||
public static boolean setEnabled(String id, boolean enabled) {
|
||||
init();
|
||||
String normalizedId = normalizeId(id);
|
||||
AddonRegistration registration = ADDONS.get(normalizedId);
|
||||
if (registration == null) return false;
|
||||
if (registration.enabled == enabled) return true;
|
||||
|
||||
registration.enabled = enabled;
|
||||
registration.restartRequired = false;
|
||||
ENABLED_OVERRIDES.put(normalizedId, enabled);
|
||||
AddonStateStore.saveEnabledOverrides(ENABLED_OVERRIDES);
|
||||
|
||||
if (enabled) {
|
||||
if (!registration.moduleConfigurationApplied) {
|
||||
configureAddonModules(registration);
|
||||
}
|
||||
if (!registration.initialized) {
|
||||
initializeAddon(registration);
|
||||
} else {
|
||||
resumeRuntimeContributions(registration);
|
||||
resumeAddon(registration, "enabled by user");
|
||||
if (registration.status != AddonStatus.ERROR) {
|
||||
registration.status = AddonStatus.ACTIVE;
|
||||
}
|
||||
}
|
||||
if (clientReady) {
|
||||
notifyClientReady(registration);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
registration.restartRequired = !registration.disabledBuiltInModules.isEmpty();
|
||||
if (!registration.initialized) {
|
||||
registration.status = AddonStatus.DISABLED;
|
||||
return true;
|
||||
}
|
||||
|
||||
suspendRuntimeContributions(registration);
|
||||
suspendAddon(registration, "disabled by user");
|
||||
registration.status = AddonStatus.DISABLED;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int activeCount() {
|
||||
int count = 0;
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
if (registration.status == AddonStatus.ACTIVE) count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void discoverEntrypoints() {
|
||||
for (var entrypoint : FabricLoader.getInstance()
|
||||
.getEntrypointContainers(LoVisualAddon.ENTRYPOINT_KEY, LoVisualAddon.class)) {
|
||||
ModMetadata metadata = entrypoint.getProvider().getMetadata();
|
||||
String id = normalizeId(metadata.getId());
|
||||
AddonDescriptor descriptor = descriptor(metadata, entrypoint.getDefinition());
|
||||
boolean enabled = ENABLED_OVERRIDES.getOrDefault(id, true);
|
||||
AddonStatus status = enabled ? AddonStatus.DISCOVERED : AddonStatus.DISABLED;
|
||||
AddonRegistration duplicate = ADDONS.get(id);
|
||||
if (duplicate != null) {
|
||||
duplicate.issue(AddonIssue.Severity.ERROR, "Duplicate addon id", metadata.getId());
|
||||
continue;
|
||||
}
|
||||
AddonRegistration registration = new AddonRegistration(descriptor, entrypoint, enabled, status);
|
||||
validateRegistration(registration);
|
||||
ADDONS.put(id, registration);
|
||||
}
|
||||
}
|
||||
|
||||
private static void configureEnabledAddons() {
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
if (registration.enabled) {
|
||||
configureAddonModules(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void configureAddonModules(AddonRegistration registration) {
|
||||
if (registration.moduleConfigurationApplied || !registration.enabled || registration.status == AddonStatus.ERROR) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
LoVisualAddon addon = addonInstance(registration);
|
||||
LoVisualModuleLoadContextImpl context = new LoVisualModuleLoadContextImpl(registration);
|
||||
addon.onConfigureModules(context);
|
||||
context.commit();
|
||||
registration.moduleConfigurationApplied = true;
|
||||
} catch (Throwable t) {
|
||||
registration.status = AddonStatus.ERROR;
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Module configuration failed", t.toString());
|
||||
DebugLog.error("Addon module configuration failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void reconcileModuleExclusions() {
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
if (registration.disabledBuiltInModules.isEmpty()) continue;
|
||||
registration.disabledBuiltInModules.removeIf(reference -> {
|
||||
if (ModuleAutoLoader.wasDisableRequestMatched(reference, registration.descriptor.id())) {
|
||||
return false;
|
||||
}
|
||||
registration.issue(
|
||||
AddonIssue.Severity.WARNING,
|
||||
"Built-in module exclusion target was not found",
|
||||
reference
|
||||
);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static void initializeEnabledAddons() {
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
if (registration.enabled && registration.status != AddonStatus.ERROR) {
|
||||
initializeAddon(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void initializeAddon(AddonRegistration registration) {
|
||||
if (registration.initialized || !registration.enabled || registration.status == AddonStatus.ERROR) return;
|
||||
if (!registration.moduleConfigurationApplied) {
|
||||
configureAddonModules(registration);
|
||||
if (registration.status == AddonStatus.ERROR) return;
|
||||
}
|
||||
try {
|
||||
LoVisualAddon addon = addonInstance(registration);
|
||||
addon.onInitialize(new LoVisualAddonContextImpl(registration));
|
||||
registration.initialized = true;
|
||||
registration.status = AddonStatus.ACTIVE;
|
||||
DebugLog.info("Addon initialized: %s", registration.descriptor.id());
|
||||
if (clientReady) {
|
||||
notifyClientReady(registration);
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
registration.status = AddonStatus.ERROR;
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Initialization failed", t.toString());
|
||||
DebugLog.error("Addon initialization failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void notifyClientReady(AddonRegistration registration) {
|
||||
if (registration == null
|
||||
|| registration.clientReadyNotified
|
||||
|| !registration.initialized
|
||||
|| !registration.enabled
|
||||
|| registration.status != AddonStatus.ACTIVE) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
registration.addon.onClientReady(
|
||||
new LoVisualAddonRuntimeContextImpl(registration.descriptor.id())
|
||||
);
|
||||
registration.clientReadyNotified = true;
|
||||
} catch (Throwable t) {
|
||||
registration.status = AddonStatus.ERROR;
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Client ready callback failed", t.toString());
|
||||
DebugLog.error("Addon client ready callback failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static LoVisualAddon addonInstance(AddonRegistration registration) {
|
||||
LoVisualAddon addon = registration.addon;
|
||||
if (addon == null) {
|
||||
addon = registration.entrypoint.getEntrypoint();
|
||||
registration.addon = addon;
|
||||
}
|
||||
return addon;
|
||||
}
|
||||
|
||||
private static void suspendAddon(AddonRegistration registration, String reason) {
|
||||
if (registration.addon == null) return;
|
||||
try {
|
||||
registration.addon.onRuntimeSuspended(new LoVisualAddonRuntimeContextImpl(registration.descriptor.id()));
|
||||
} catch (Throwable t) {
|
||||
registration.status = AddonStatus.ERROR;
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Runtime suspend failed", t.toString());
|
||||
DebugLog.error("Addon runtime suspend failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void resumeAddon(AddonRegistration registration, String reason) {
|
||||
if (registration.addon == null) return;
|
||||
try {
|
||||
registration.addon.onRuntimeResumed(new LoVisualAddonRuntimeContextImpl(registration.descriptor.id()));
|
||||
} catch (Throwable t) {
|
||||
registration.status = AddonStatus.ERROR;
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Runtime resume failed", t.toString());
|
||||
DebugLog.error("Addon runtime resume failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void shutdownAddon(AddonRegistration registration, String reason) {
|
||||
if (registration.addon == null) return;
|
||||
try {
|
||||
registration.addon.onShutdown(new LoVisualAddonRuntimeContextImpl(registration.descriptor.id()));
|
||||
} catch (Throwable t) {
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Shutdown failed", t.toString());
|
||||
DebugLog.error("Addon shutdown failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void suspendRuntimeContributions(AddonRegistration registration) {
|
||||
registration.suspendedModules.clear();
|
||||
registration.suspendedDraggableHudElements.clear();
|
||||
registration.suspendedStaticHudElements.clear();
|
||||
for (String id : registration.modules) {
|
||||
Module module = ModuleManager.get(id);
|
||||
if (module != null) {
|
||||
registration.suspendedModules.put(id, module.isEnabled());
|
||||
ModuleManager.setRuntimeEnabledTransient(id, false);
|
||||
}
|
||||
}
|
||||
for (String id : registration.draggableHudElements) {
|
||||
DraggableHudElement element = DraggableHudElementRegistry.getById(id);
|
||||
if (element != null) {
|
||||
registration.suspendedDraggableHudElements.put(id, element.isEnabled());
|
||||
element.setRuntimeEnabledTransient(false);
|
||||
}
|
||||
}
|
||||
for (String id : registration.staticHudElements) {
|
||||
AbstractHudElement element = StaticHudElementRegistry.getById(id);
|
||||
if (element != null) {
|
||||
registration.suspendedStaticHudElements.put(id, element.isEnabled());
|
||||
element.setRuntimeEnabledTransient(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void resumeRuntimeContributions(AddonRegistration registration) {
|
||||
for (String id : registration.modules) {
|
||||
Boolean enabled = registration.suspendedModules.get(id);
|
||||
if (enabled != null) {
|
||||
ModuleManager.setRuntimeEnabledTransient(id, enabled);
|
||||
}
|
||||
}
|
||||
for (String id : registration.draggableHudElements) {
|
||||
Boolean enabled = registration.suspendedDraggableHudElements.get(id);
|
||||
DraggableHudElement element = DraggableHudElementRegistry.getById(id);
|
||||
if (enabled != null && element != null) {
|
||||
element.setRuntimeEnabledTransient(enabled);
|
||||
}
|
||||
}
|
||||
for (String id : registration.staticHudElements) {
|
||||
Boolean enabled = registration.suspendedStaticHudElements.get(id);
|
||||
AbstractHudElement element = StaticHudElementRegistry.getById(id);
|
||||
if (enabled != null && element != null) {
|
||||
element.setRuntimeEnabledTransient(enabled);
|
||||
}
|
||||
}
|
||||
registration.suspendedModules.clear();
|
||||
registration.suspendedDraggableHudElements.clear();
|
||||
registration.suspendedStaticHudElements.clear();
|
||||
}
|
||||
|
||||
public static void noteModuleOwner(String addonId, String moduleId) {
|
||||
|
||||
if (moduleId != null && !moduleId.isBlank()) {
|
||||
MODULE_OWNERS.put(normalizeId(moduleId), normalizeId(addonId));
|
||||
}
|
||||
}
|
||||
|
||||
public static void noteDraggableHudOwner(String addonId, String elementId) {
|
||||
|
||||
if (elementId != null && !elementId.isBlank()) {
|
||||
DRAGGABLE_HUD_OWNERS.put(normalizeId(elementId), normalizeId(addonId));
|
||||
}
|
||||
}
|
||||
|
||||
public static void noteStaticHudOwner(String addonId, String elementId) {
|
||||
|
||||
if (elementId != null && !elementId.isBlank()) {
|
||||
STATIC_HUD_OWNERS.put(normalizeId(elementId), normalizeId(addonId));
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateRegistration(AddonRegistration registration) {
|
||||
if (registration.descriptor.apiVersion() != LoVisualAddon.API_VERSION) {
|
||||
registration.issue(
|
||||
AddonIssue.Severity.WARNING,
|
||||
"Addon API version differs from client API",
|
||||
"addon=" + registration.descriptor.apiVersion() + ", client=" + LoVisualAddon.API_VERSION
|
||||
);
|
||||
}
|
||||
if (registration.descriptor.iconPath() == null || registration.descriptor.iconPath().isBlank()) {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Addon icon is missing", "Add icon in fabric.mod.json");
|
||||
}
|
||||
if (registration.descriptor.entrypointDefinition() == null
|
||||
|| registration.descriptor.entrypointDefinition().isBlank()) {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Entrypoint definition is unavailable", "");
|
||||
}
|
||||
}
|
||||
|
||||
private static AddonDescriptor descriptor(ModMetadata metadata, String entrypointDefinition) {
|
||||
List<String> authors = metadata.getAuthors().stream()
|
||||
.map(person -> person.getName() == null ? "" : person.getName())
|
||||
.filter(name -> !name.isBlank())
|
||||
.toList();
|
||||
return new AddonDescriptor(
|
||||
normalizeId(metadata.getId()),
|
||||
blankFallback(metadata.getName(), metadata.getId()),
|
||||
String.valueOf(metadata.getVersion()),
|
||||
metadata.getDescription() == null ? "" : metadata.getDescription(),
|
||||
authors,
|
||||
metadata.getIconPath(64).or(() -> metadata.getIconPath(32)).orElse(""),
|
||||
apiVersion(metadata),
|
||||
entrypointDefinition
|
||||
);
|
||||
}
|
||||
|
||||
private static int apiVersion(ModMetadata metadata) {
|
||||
CustomValue value = metadata.getCustomValue(ADDON_METADATA_KEY);
|
||||
if (value == null || value.getType() != CustomValue.CvType.OBJECT) return LoVisualAddon.API_VERSION;
|
||||
CustomValue api = value.getAsObject().get("api");
|
||||
if (api == null || api.getType() != CustomValue.CvType.NUMBER) return LoVisualAddon.API_VERSION;
|
||||
return api.getAsNumber().intValue();
|
||||
}
|
||||
|
||||
private static String blankFallback(String value, String fallback) {
|
||||
return value == null || value.isBlank() ? fallback : value;
|
||||
}
|
||||
|
||||
private static String normalizeId(String id) {
|
||||
return id == null ? "" : id.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.core;
|
||||
|
||||
import dev.loki.lovisual.api.v0.addon.LoVisualAddon;
|
||||
import net.fabricmc.loader.api.entrypoint.EntrypointContainer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.addon.core.AddonDescriptor;
|
||||
import dev.loki.lovisual.addon.core.AddonIssue;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonSnapshot;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonStatus;
|
||||
|
||||
public final class AddonRegistration {
|
||||
public final AddonDescriptor descriptor;
|
||||
|
||||
public final EntrypointContainer<LoVisualAddon> entrypoint;
|
||||
|
||||
public final List<String> modules = new ArrayList<>();
|
||||
|
||||
public final List<String> disabledBuiltInModules = new ArrayList<>();
|
||||
|
||||
public final List<String> draggableHudElements = new ArrayList<>();
|
||||
|
||||
public final List<String> staticHudElements = new ArrayList<>();
|
||||
|
||||
public final List<String> commands = new ArrayList<>();
|
||||
|
||||
public final List<String> clickGuiSections = new ArrayList<>();
|
||||
|
||||
public final List<String> moduleExtensions = new ArrayList<>();
|
||||
|
||||
public final List<String> irisPatchManifests = new ArrayList<>();
|
||||
|
||||
public final List<String> renderCallbacks = new ArrayList<>();
|
||||
|
||||
public final List<String> postProcessPasses = new ArrayList<>();
|
||||
|
||||
final List<AddonIssue> issues = new ArrayList<>();
|
||||
final Map<String, Boolean> suspendedModules = new LinkedHashMap<>();
|
||||
final Map<String, Boolean> suspendedDraggableHudElements = new LinkedHashMap<>();
|
||||
final Map<String, Boolean> suspendedStaticHudElements = new LinkedHashMap<>();
|
||||
LoVisualAddon addon;
|
||||
boolean moduleConfigurationApplied;
|
||||
boolean initialized;
|
||||
boolean clientReadyNotified;
|
||||
AddonStatus status;
|
||||
boolean enabled;
|
||||
public boolean restartRequired;
|
||||
|
||||
|
||||
AddonRegistration(AddonDescriptor descriptor,
|
||||
EntrypointContainer<LoVisualAddon> entrypoint,
|
||||
boolean enabled,
|
||||
AddonStatus status) {
|
||||
this.descriptor = descriptor;
|
||||
this.entrypoint = entrypoint;
|
||||
this.enabled = enabled;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
AddonSnapshot snapshot() {
|
||||
return new AddonSnapshot(
|
||||
descriptor.id(),
|
||||
descriptor.name(),
|
||||
descriptor.version(),
|
||||
descriptor.description(),
|
||||
descriptor.authors(),
|
||||
descriptor.iconPath(),
|
||||
descriptor.apiVersion(),
|
||||
status,
|
||||
enabled,
|
||||
restartRequired,
|
||||
modules.size(),
|
||||
draggableHudElements.size(),
|
||||
staticHudElements.size(),
|
||||
commands.size(),
|
||||
clickGuiSections.size(),
|
||||
moduleExtensions.size(),
|
||||
irisPatchManifests.size(),
|
||||
List.copyOf(issues)
|
||||
);
|
||||
}
|
||||
|
||||
public void issue(AddonIssue.Severity severity, String message, String detail) {
|
||||
|
||||
issues.add(new AddonIssue(descriptor.id(), severity, message, detail));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.manager;
|
||||
|
||||
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
|
||||
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiRenderContext;
|
||||
import dev.loki.lovisual.features.gui.clickgui.render.ClickGuiRenderer;
|
||||
import dev.loki.lovisual.features.gui.clickgui.sections.ClickGuiSection;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
|
||||
public enum ClickGuiSectionManager {
|
||||
;
|
||||
|
||||
private static final Map<String, Entry> SECTIONS = new LinkedHashMap<>();
|
||||
|
||||
public static synchronized boolean register(String addonId,
|
||||
String sectionId,
|
||||
String label,
|
||||
LoVisualClickGuiSection section) {
|
||||
String normalizedAddonId = normalize(addonId);
|
||||
String normalizedSectionId = normalize(sectionId);
|
||||
if (normalizedAddonId.isBlank() || normalizedSectionId.isBlank() || section == null) {
|
||||
return false;
|
||||
}
|
||||
String id = normalizedAddonId + ":" + normalizedSectionId;
|
||||
if (SECTIONS.containsKey(id)) {
|
||||
return false;
|
||||
}
|
||||
String title = label == null || label.isBlank() ? normalizedSectionId : label.trim();
|
||||
SECTIONS.put(id, new Entry(
|
||||
normalizedAddonId,
|
||||
id,
|
||||
normalizedSectionId,
|
||||
title,
|
||||
new AddonSectionAdapter(section)
|
||||
));
|
||||
return true;
|
||||
}
|
||||
|
||||
public static synchronized void unregisterAddon(String addonId) {
|
||||
String normalizedAddonId = normalize(addonId);
|
||||
SECTIONS.entrySet().removeIf(entry -> {
|
||||
if (!entry.getValue().addonId().equals(normalizedAddonId)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
entry.getValue().section().onDeselected();
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public static synchronized List<Entry> sections() {
|
||||
return SECTIONS.values().stream()
|
||||
.filter(entry -> AddonManager.isActive(entry.addonId()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value == null ? "" : value.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
public record Entry(String addonId,
|
||||
String id,
|
||||
String localId,
|
||||
String label,
|
||||
ClickGuiSection section) {
|
||||
}
|
||||
|
||||
private record AddonSectionAdapter(LoVisualClickGuiSection section) implements ClickGuiSection {
|
||||
@Override
|
||||
public void layout(float x, float y, float w, float h) {
|
||||
section.layout(x, y, w, h);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(float mouseX, float mouseY) {
|
||||
section.render(
|
||||
new LoVisualClickGuiRenderContext(
|
||||
ClickGuiRenderer.currentRenderer(),
|
||||
ClickGuiRenderer.getInterRegular(),
|
||||
ClickGuiRenderer.getInterMedium()
|
||||
),
|
||||
mouseX,
|
||||
mouseY
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderGlassPass(float alphaFactor) {
|
||||
section.renderGlassPass(alphaFactor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mousePressed(float mouseX, float mouseY, int button) {
|
||||
return section.mousePressed(mouseX, mouseY, button);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mouseReleased(float mouseX, float mouseY, int button) {
|
||||
section.mouseReleased(mouseX, mouseY, button);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mouseScrolled(float mouseX, float mouseY, double amount) {
|
||||
return section.mouseScrolled(mouseX, mouseY, amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
|
||||
return section.keyPressed(keyCode, scanCode, modifiers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean charTyped(char chr, int modifiers) {
|
||||
return section.charTyped(chr, modifiers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSelected() {
|
||||
section.onSelected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeselected() {
|
||||
section.onDeselected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisible() {
|
||||
return section.isVisible();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,173 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.manager;
|
||||
|
||||
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.core.ModuleManager;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.addon.context.ModuleExtensionContextImpl;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
|
||||
public enum ModuleExtensionManager {
|
||||
;
|
||||
|
||||
private static final Map<String, List<RegisteredExtension>> EXTENSIONS = new LinkedHashMap<>();
|
||||
|
||||
public static boolean register(String addonId, String moduleId, LoVisualModuleExtension extension) {
|
||||
if (extension == null || moduleId == null || moduleId.isBlank()) return false;
|
||||
Module module = ModuleManager.get(moduleId);
|
||||
if (module == null) {
|
||||
DebugLog.warn("[Addons] Module extension target missing: addon=%s module=%s", addonId, moduleId);
|
||||
return false;
|
||||
}
|
||||
String normalized = normalize(moduleId);
|
||||
RegisteredExtension registered = new RegisteredExtension(addonId, extension);
|
||||
EXTENSIONS.computeIfAbsent(normalized, ignored -> new ArrayList<>()).add(registered);
|
||||
try {
|
||||
extension.onRegister(new ModuleExtensionContextImpl(addonId, module));
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("[Addons] Module extension registration failed: %s", t, normalized);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int count() {
|
||||
int count = 0;
|
||||
for (List<RegisteredExtension> list : EXTENSIONS.values()) {
|
||||
count += list.size();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
public static boolean beforeEnable(Module module) {
|
||||
return all(module, extension -> extension.beforeEnable(module));
|
||||
}
|
||||
|
||||
public static void afterEnable(Module module) {
|
||||
each(module, extension -> extension.afterEnable(module));
|
||||
}
|
||||
|
||||
public static boolean beforeDisable(Module module) {
|
||||
return all(module, extension -> extension.beforeDisable(module));
|
||||
}
|
||||
|
||||
public static void afterDisable(Module module) {
|
||||
each(module, extension -> extension.afterDisable(module));
|
||||
}
|
||||
|
||||
public static boolean beforeTick(Module module) {
|
||||
return all(module, extension -> extension.beforeTick(module));
|
||||
}
|
||||
|
||||
public static void afterTick(Module module) {
|
||||
each(module, extension -> extension.afterTick(module));
|
||||
}
|
||||
|
||||
public static boolean beforeFrame(Module module, float frameDeltaTicks) {
|
||||
return all(module, extension -> extension.beforeFrame(module, frameDeltaTicks));
|
||||
}
|
||||
|
||||
public static void afterFrame(Module module, float frameDeltaTicks) {
|
||||
each(module, extension -> extension.afterFrame(module, frameDeltaTicks));
|
||||
}
|
||||
|
||||
public static boolean beforeHudRender(Module module,
|
||||
Renderer2D renderer,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor ctx,
|
||||
float tickDelta) {
|
||||
return all(module, extension -> extension.beforeHudRender(module, renderer, textRenderer, ctx, tickDelta));
|
||||
}
|
||||
|
||||
public static void afterHudRender(Module module,
|
||||
Renderer2D renderer,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor ctx,
|
||||
float tickDelta) {
|
||||
each(module, extension -> extension.afterHudRender(module, renderer, textRenderer, ctx, tickDelta));
|
||||
}
|
||||
|
||||
public static boolean beforeWorldRender(Module module,
|
||||
Renderer3D renderer,
|
||||
Renderer3D depthRenderer,
|
||||
float tickDelta) {
|
||||
return all(module, extension -> extension.beforeWorldRender(module, renderer, depthRenderer, tickDelta));
|
||||
}
|
||||
|
||||
public static void afterWorldRender(Module module,
|
||||
Renderer3D renderer,
|
||||
Renderer3D depthRenderer,
|
||||
float tickDelta) {
|
||||
each(module, extension -> extension.afterWorldRender(module, renderer, depthRenderer, tickDelta));
|
||||
}
|
||||
|
||||
private static boolean all(Module module, ExtensionBooleanCall call) {
|
||||
List<RegisteredExtension> extensions = extensions(module);
|
||||
if (extensions.isEmpty()) return true;
|
||||
boolean proceed = true;
|
||||
for (RegisteredExtension registered : extensions) {
|
||||
if (!AddonManager.isActive(registered.addonId())) continue;
|
||||
try {
|
||||
proceed &= call.invoke(registered.extension());
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("[Addons] Module extension hook failed: addon=%s module=%s",
|
||||
t, registered.addonId(), module == null ? "" : module.name());
|
||||
}
|
||||
}
|
||||
return proceed;
|
||||
}
|
||||
|
||||
private static void each(Module module, ExtensionVoidCall call) {
|
||||
List<RegisteredExtension> extensions = extensions(module);
|
||||
if (extensions.isEmpty()) return;
|
||||
for (RegisteredExtension registered : extensions) {
|
||||
if (!AddonManager.isActive(registered.addonId())) continue;
|
||||
try {
|
||||
call.invoke(registered.extension());
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("[Addons] Module extension hook failed: addon=%s module=%s",
|
||||
t, registered.addonId(), module == null ? "" : module.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<RegisteredExtension> extensions(Module module) {
|
||||
if (module == null) return List.of();
|
||||
List<RegisteredExtension> list = EXTENSIONS.get(normalize(module.name()));
|
||||
return list == null ? List.of() : List.copyOf(list);
|
||||
}
|
||||
|
||||
private static String normalize(String id) {
|
||||
return id == null ? "" : id.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ExtensionBooleanCall {
|
||||
boolean invoke(LoVisualModuleExtension extension);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ExtensionVoidCall {
|
||||
void invoke(LoVisualModuleExtension extension);
|
||||
}
|
||||
|
||||
private record RegisteredExtension(String addonId, LoVisualModuleExtension extension) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,194 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.pipeline;
|
||||
|
||||
import com.mojang.blaze3d.textures.GpuTextureView;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualPostProcessCallback;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualPostProcessContext;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualRenderCallback;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualRenderContext;
|
||||
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
|
||||
import dev.loki.lovisual.features.module.phase.HudPhase;
|
||||
import dev.loki.lovisual.features.module.phase.WorldPhase;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessManager;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessPass;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
|
||||
public enum AddonRenderPipelineManager {
|
||||
;
|
||||
|
||||
private static final Map<LoVisualRenderStage, List<RegisteredRenderCallback>> CALLBACKS =
|
||||
new EnumMap<>(LoVisualRenderStage.class);
|
||||
|
||||
static {
|
||||
for (LoVisualRenderStage stage : LoVisualRenderStage.values()) {
|
||||
CALLBACKS.put(stage, new ArrayList<>());
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized boolean register(String addonId,
|
||||
String callbackId,
|
||||
LoVisualRenderStage stage,
|
||||
LoVisualRenderCallback callback) {
|
||||
String normalizedAddonId = normalize(addonId);
|
||||
String normalizedCallbackId = normalize(callbackId);
|
||||
if (normalizedAddonId.isBlank() || normalizedCallbackId.isBlank() || stage == null || callback == null) {
|
||||
return false;
|
||||
}
|
||||
List<RegisteredRenderCallback> callbacks = CALLBACKS.get(stage);
|
||||
for (RegisteredRenderCallback registered : callbacks) {
|
||||
if (registered.addonId().equals(normalizedAddonId) && registered.callbackId().equals(normalizedCallbackId)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
callbacks.add(new RegisteredRenderCallback(normalizedAddonId, normalizedCallbackId, callback));
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean hasActiveCallbacks(LoVisualRenderStage stage) {
|
||||
if (stage == null) return false;
|
||||
List<RegisteredRenderCallback> callbacks;
|
||||
synchronized (AddonRenderPipelineManager.class) {
|
||||
callbacks = List.copyOf(CALLBACKS.get(stage));
|
||||
}
|
||||
for (RegisteredRenderCallback callback : callbacks) {
|
||||
if (AddonManager.isActive(callback.addonId())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean registerPostProcess(String addonId,
|
||||
String passId,
|
||||
PostProcessPass.Phase phase,
|
||||
int priority,
|
||||
LoVisualPostProcessCallback callback) {
|
||||
String normalizedAddonId = normalize(addonId);
|
||||
String normalizedPassId = normalize(passId);
|
||||
if (normalizedAddonId.isBlank() || normalizedPassId.isBlank() || phase == null || callback == null) {
|
||||
return false;
|
||||
}
|
||||
PostProcessManager.register(new AddonPostProcessPass(normalizedAddonId, normalizedPassId, phase, priority, callback));
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void render2D(LoVisualRenderStage stage,
|
||||
HudPhase hudPhase,
|
||||
Renderer2D renderer,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor guiContext,
|
||||
float tickDelta) {
|
||||
render(stage, hudPhase, null, renderer, null, null, textRenderer, guiContext, null, tickDelta);
|
||||
}
|
||||
|
||||
public static void render3D(LoVisualRenderStage stage,
|
||||
WorldPhase worldPhase,
|
||||
Renderer3D renderer,
|
||||
Renderer3D depthRenderer,
|
||||
PoseStack poseStack,
|
||||
float tickDelta) {
|
||||
render(stage, null, worldPhase, null, renderer, depthRenderer, null, null, poseStack, tickDelta);
|
||||
}
|
||||
|
||||
public static synchronized void unregisterAddon(String addonId) {
|
||||
String normalizedAddonId = normalize(addonId);
|
||||
for (List<RegisteredRenderCallback> callbacks : CALLBACKS.values()) {
|
||||
callbacks.removeIf(callback -> callback.addonId().equals(normalizedAddonId));
|
||||
}
|
||||
}
|
||||
|
||||
private static void render(LoVisualRenderStage stage,
|
||||
HudPhase hudPhase,
|
||||
WorldPhase worldPhase,
|
||||
Renderer2D renderer2D,
|
||||
Renderer3D renderer3D,
|
||||
Renderer3D depthRenderer3D,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor guiContext,
|
||||
PoseStack poseStack,
|
||||
float tickDelta) {
|
||||
List<RegisteredRenderCallback> callbacks;
|
||||
synchronized (AddonRenderPipelineManager.class) {
|
||||
callbacks = List.copyOf(CALLBACKS.get(stage));
|
||||
}
|
||||
for (RegisteredRenderCallback registered : callbacks) {
|
||||
if (!AddonManager.isActive(registered.addonId())) continue;
|
||||
try {
|
||||
registered.callback().render(new LoVisualRenderContext(
|
||||
registered.addonId(),
|
||||
registered.callbackId(),
|
||||
stage,
|
||||
hudPhase,
|
||||
worldPhase,
|
||||
renderer2D,
|
||||
renderer3D,
|
||||
depthRenderer3D,
|
||||
textRenderer,
|
||||
guiContext,
|
||||
poseStack,
|
||||
tickDelta
|
||||
));
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("[Addons] Render callback failed: addon=%s id=%s",
|
||||
t, registered.addonId(), registered.callbackId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalize(String id) {
|
||||
return id == null ? "" : id.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private record RegisteredRenderCallback(String addonId,
|
||||
String callbackId,
|
||||
LoVisualRenderCallback callback) {
|
||||
}
|
||||
|
||||
private record AddonPostProcessPass(String addonId,
|
||||
String passId,
|
||||
PostProcessPass.Phase phase,
|
||||
int priority,
|
||||
LoVisualPostProcessCallback callback) implements PostProcessPass {
|
||||
@Override
|
||||
public boolean isActive() {
|
||||
return AddonManager.isActive(addonId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean render(GpuTextureView src, GpuTextureView dst, float tickDelta) {
|
||||
if (!isActive()) return false;
|
||||
try {
|
||||
return callback.render(new LoVisualPostProcessContext(addonId, passId, phase, src, dst, tickDelta));
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("[Addons] Post-process callback failed: addon=%s id=%s", t, addonId, passId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPriority() {
|
||||
return priority;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Phase getPhase() {
|
||||
return phase;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.pipeline;
|
||||
|
||||
import java.util.List;
|
||||
import dev.loki.lovisual.addon.core.AddonIssue;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonStatus;
|
||||
|
||||
public record AddonSnapshot(
|
||||
String id,
|
||||
String name,
|
||||
String version,
|
||||
String description,
|
||||
List<String> authors,
|
||||
String iconPath,
|
||||
int apiVersion,
|
||||
AddonStatus status,
|
||||
boolean enabled,
|
||||
boolean restartRequired,
|
||||
int modules,
|
||||
int draggableHudElements,
|
||||
int staticHudElements,
|
||||
int commands,
|
||||
int clickGuiSections,
|
||||
int moduleExtensions,
|
||||
int irisPatchManifests,
|
||||
List<AddonIssue> issues
|
||||
) {
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.pipeline;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class AddonStateStore {
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
private AddonStateStore() {
|
||||
}
|
||||
|
||||
public static Map<String, Boolean> loadEnabledOverrides() {
|
||||
|
||||
Path file = stateFile();
|
||||
if (!Files.isRegularFile(file)) return new HashMap<>();
|
||||
try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
|
||||
State state = GSON.fromJson(reader, State.class);
|
||||
if (state == null || state.enabled == null) return new HashMap<>();
|
||||
return new HashMap<>(state.enabled);
|
||||
} catch (Throwable ignored) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveEnabledOverrides(Map<String, Boolean> enabled) {
|
||||
|
||||
Path file = stateFile();
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
State state = new State();
|
||||
state.enabled = new HashMap<>(enabled);
|
||||
try (Writer writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
|
||||
GSON.toJson(state, writer);
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private static Path stateFile() {
|
||||
return FabricLoader.getInstance().getConfigDir()
|
||||
.resolve("lovisual")
|
||||
.resolve("addons.json");
|
||||
}
|
||||
|
||||
private static final class State {
|
||||
Map<String, Boolean> enabled = new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.pipeline;
|
||||
|
||||
public enum AddonStatus {
|
||||
DISCOVERED,
|
||||
DISABLED,
|
||||
ACTIVE,
|
||||
SUSPENDED,
|
||||
ERROR,
|
||||
SHUTDOWN
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.addon;
|
||||
|
||||
/**
|
||||
* Fabric entrypoint contract for LoVisual addons.
|
||||
*
|
||||
* <p>Declare it in fabric.mod.json under the {@value #ENTRYPOINT_KEY} entrypoint.
|
||||
*/
|
||||
public interface LoVisualAddon {
|
||||
String ENTRYPOINT_KEY = "lovisual:addon";
|
||||
int API_VERSION = 0;
|
||||
|
||||
/**
|
||||
* Called before LoVisual auto-loads its built-in modules.
|
||||
*
|
||||
* <p>Use this hook only for startup module exclusions. Normal addon registration
|
||||
* still belongs in {@link #onInitialize(LoVisualAddonContext)}.</p>
|
||||
*/
|
||||
default void onConfigureModules(LoVisualModuleLoadContext context) {
|
||||
}
|
||||
|
||||
void onInitialize(LoVisualAddonContext context);
|
||||
|
||||
/**
|
||||
* Called after all built-in and addon module configs have been loaded and applied.
|
||||
* This is the safe startup hook for mutating settings of existing modules.
|
||||
*/
|
||||
default void onClientReady(LoVisualAddonRuntimeContext context) {
|
||||
}
|
||||
|
||||
default void onRuntimeSuspended(LoVisualAddonRuntimeContext context) {
|
||||
}
|
||||
|
||||
default void onRuntimeResumed(LoVisualAddonRuntimeContext context) {
|
||||
}
|
||||
|
||||
default void onShutdown(LoVisualAddonRuntimeContext context) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.addon;
|
||||
|
||||
import dev.loki.lovisual.events.meta.UsedImplicitly;
|
||||
import dev.loki.lovisual.features.command.util.ClientCommand;
|
||||
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
|
||||
import dev.loki.lovisual.features.gui.hud.base.AbstractHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualPostProcessCallback;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualRenderCallback;
|
||||
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
|
||||
import com.mojang.blaze3d.pipeline.RenderPipeline;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessPass;
|
||||
import net.fabricmc.loader.api.ModContainer;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public interface LoVisualAddonContext extends LoVisualAddonRuntimeContext {
|
||||
@UsedImplicitly
|
||||
ModContainer modContainer();
|
||||
@UsedImplicitly
|
||||
Path gameDir();
|
||||
|
||||
Path configDir();
|
||||
@UsedImplicitly
|
||||
Path addonConfigDir();
|
||||
@UsedImplicitly
|
||||
void registerModule(Module module);
|
||||
@UsedImplicitly
|
||||
void registerDraggableHudElement(DraggableHudElement element);
|
||||
@UsedImplicitly
|
||||
void registerStaticHudElement(AbstractHudElement element);
|
||||
@UsedImplicitly
|
||||
void registerCommand(ClientCommand command);
|
||||
@UsedImplicitly
|
||||
void registerClickGuiSection(String sectionId, String label, LoVisualClickGuiSection section);
|
||||
@UsedImplicitly
|
||||
void registerModuleExtension(String moduleId, LoVisualModuleExtension extension);
|
||||
@UsedImplicitly
|
||||
void registerIrisShaderPatchManifest(String manifestResourcePath);
|
||||
@UsedImplicitly
|
||||
void registerRenderCallback(String callbackId, LoVisualRenderStage stage, LoVisualRenderCallback callback);
|
||||
@UsedImplicitly
|
||||
void registerPostProcessPass(String passId, PostProcessPass.Phase phase, int priority, LoVisualPostProcessCallback callback);
|
||||
@UsedImplicitly
|
||||
RenderPipeline registerRenderPipeline(RenderPipeline pipeline);
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.addon;
|
||||
|
||||
import dev.loki.lovisual.api.v0.client.LoVisualClientApi;
|
||||
|
||||
public interface LoVisualAddonRuntimeContext {
|
||||
String addonId();
|
||||
|
||||
LoVisualClientApi client();
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.addon;
|
||||
|
||||
import dev.loki.lovisual.events.meta.UsedImplicitly;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.core.ModuleInfo;
|
||||
|
||||
/**
|
||||
* Early addon context used before LoVisual's built-in modules are instantiated.
|
||||
*
|
||||
* <p>Only enabled addons receive this callback. Exclusions are startup-only: changing
|
||||
* an addon's enabled state after module discovery requires a client restart for the
|
||||
* built-in module set to be rebuilt.</p>
|
||||
*/
|
||||
public interface LoVisualModuleLoadContext {
|
||||
@UsedImplicitly
|
||||
String addonId();
|
||||
|
||||
/**
|
||||
* Prevents an auto-loaded built-in module from being instantiated.
|
||||
*
|
||||
* <p>The reference may be a {@code ModuleInfo.id}, module alias, simple class name,
|
||||
* or fully-qualified class name.</p>
|
||||
*
|
||||
* @return {@code true} when the exclusion was accepted for the current startup;
|
||||
* {@code false} when the reference is invalid or module discovery has already started
|
||||
*/
|
||||
@UsedImplicitly
|
||||
boolean disableBuiltInModule(String moduleReference);
|
||||
|
||||
/**
|
||||
* Class-based convenience overload for addons that directly depend on a built-in module type.
|
||||
*/
|
||||
@UsedImplicitly
|
||||
default boolean disableBuiltInModule(Class<? extends Module> moduleType) {
|
||||
return moduleType != null && disableBuiltInModule(moduleType.getName());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.clickgui;
|
||||
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
|
||||
public record LoVisualClickGuiRenderContext(
|
||||
Renderer2D renderer,
|
||||
TextRenderer regularFont,
|
||||
TextRenderer mediumFont
|
||||
) {
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.clickgui;
|
||||
|
||||
public interface LoVisualClickGuiSection {
|
||||
default void layout(float x, float y, float w, float h) {
|
||||
}
|
||||
|
||||
default void render(LoVisualClickGuiRenderContext context, float mouseX, float mouseY) {
|
||||
}
|
||||
|
||||
default void renderGlassPass(float alphaFactor) {
|
||||
}
|
||||
|
||||
default boolean mousePressed(float mouseX, float mouseY, int button) {
|
||||
return false;
|
||||
}
|
||||
|
||||
default void mouseReleased(float mouseX, float mouseY, int button) {
|
||||
}
|
||||
|
||||
default boolean mouseScrolled(float mouseX, float mouseY, double amount) {
|
||||
return false;
|
||||
}
|
||||
|
||||
default boolean keyPressed(int keyCode, int scanCode, int modifiers) {
|
||||
return false;
|
||||
}
|
||||
|
||||
default boolean charTyped(char chr, int modifiers) {
|
||||
return false;
|
||||
}
|
||||
|
||||
default void onSelected() {
|
||||
}
|
||||
|
||||
default void onDeselected() {
|
||||
}
|
||||
|
||||
default boolean isVisible() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.client;
|
||||
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.core.ModuleManager;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class LoVisualClientApi {
|
||||
private static final LoVisualClientApi INSTANCE = new LoVisualClientApi();
|
||||
|
||||
private LoVisualClientApi() {
|
||||
}
|
||||
|
||||
public static LoVisualClientApi get() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public List<Module> modules() {
|
||||
return ModuleManager.getModules();
|
||||
}
|
||||
|
||||
public Module module(String id) {
|
||||
return ModuleManager.get(id);
|
||||
}
|
||||
|
||||
public boolean isModuleEnabled(String id) {
|
||||
return ModuleManager.isEnabled(id);
|
||||
}
|
||||
|
||||
public void setModuleEnabled(String id, boolean enabled) {
|
||||
ModuleManager.setEnabled(id, enabled);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.module;
|
||||
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
|
||||
public interface LoVisualModuleExtension {
|
||||
default void onRegister(ModuleExtensionContext context) {
|
||||
}
|
||||
|
||||
default boolean beforeEnable(Module module) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterEnable(Module module) {
|
||||
}
|
||||
|
||||
default boolean beforeDisable(Module module) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterDisable(Module module) {
|
||||
}
|
||||
|
||||
default boolean beforeTick(Module module) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterTick(Module module) {
|
||||
}
|
||||
|
||||
default boolean beforeFrame(Module module, float frameDeltaTicks) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterFrame(Module module, float frameDeltaTicks) {
|
||||
}
|
||||
|
||||
default boolean beforeHudRender(Module module,
|
||||
Renderer2D renderer,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor ctx,
|
||||
float tickDelta) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterHudRender(Module module,
|
||||
Renderer2D renderer,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor ctx,
|
||||
float tickDelta) {
|
||||
}
|
||||
|
||||
default boolean beforeWorldRender(Module module,
|
||||
Renderer3D renderer,
|
||||
Renderer3D depthRenderer,
|
||||
float tickDelta) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterWorldRender(Module module,
|
||||
Renderer3D renderer,
|
||||
Renderer3D depthRenderer,
|
||||
float tickDelta) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.module;
|
||||
|
||||
import dev.loki.lovisual.config.definition.SettingDef;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
|
||||
public interface ModuleExtensionContext {
|
||||
String addonId();
|
||||
|
||||
String moduleId();
|
||||
|
||||
Module module();
|
||||
|
||||
void addSetting(SettingDef setting);
|
||||
|
||||
ConfigValue<?> getConfigValue(String configName);
|
||||
|
||||
boolean addModeOption(String configName, String option);
|
||||
}
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render;
|
||||
|
||||
import com.mojang.blaze3d.PrimitiveTopology;
|
||||
import com.mojang.blaze3d.pipeline.BlendFunction;
|
||||
import com.mojang.blaze3d.pipeline.RenderPipeline;
|
||||
import com.mojang.blaze3d.shaders.UniformType;
|
||||
import com.mojang.blaze3d.vertex.VertexFormat;
|
||||
import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines;
|
||||
import dev.loki.lovisual.render.engine.pipeline.DepthTestFunction;
|
||||
import dev.loki.lovisual.render.engine.pipeline.ExtendedRenderPipelineBuilder;
|
||||
import dev.loki.lovisual.render.engine.rhi.clip.ShapeClipRenderPassContract;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public final class LoVisualRenderPipelineBuilder {
|
||||
private final ExtendedRenderPipelineBuilder delegate;
|
||||
|
||||
private LoVisualRenderPipelineBuilder(RenderPipeline.Snippet... snippets) {
|
||||
this.delegate = new ExtendedRenderPipelineBuilder(snippets);
|
||||
}
|
||||
|
||||
public static LoVisualRenderPipelineBuilder create(RenderPipeline.Snippet... snippets) {
|
||||
return new LoVisualRenderPipelineBuilder(snippets);
|
||||
}
|
||||
|
||||
public static RenderPipeline.Snippet meshUniforms() {
|
||||
return LoVisualRenderPipelines.meshUniforms();
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder location(Identifier id) {
|
||||
delegate.withLocation(id);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder vertexFormat(VertexFormat format, PrimitiveTopology mode) {
|
||||
delegate.withVertexFormat(format, mode);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder vertexShader(Identifier id) {
|
||||
delegate.withVertexShader(id);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder fragmentShader(Identifier id) {
|
||||
delegate.withFragmentShader(id);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder depthTest(DepthTestFunction function) {
|
||||
delegate.withDepthTestFunction(function);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder depthWrite(boolean write) {
|
||||
delegate.withDepthWrite(write);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder blend(BlendFunction blend) {
|
||||
delegate.withBlend(blend);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder cull(boolean cull) {
|
||||
delegate.withCull(cull);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder sampler(String name) {
|
||||
delegate.withSampler(name);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder uniform(String name, UniformType type) {
|
||||
delegate.withUniform(name, type);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder lineSmooth() {
|
||||
delegate.withLineSmooth();
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder shapeClipSupport() {
|
||||
delegate.withShapeClipSupport();
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder shapeClipContract(ShapeClipRenderPassContract contract) {
|
||||
delegate.withShapeClipContract(contract);
|
||||
return this;
|
||||
}
|
||||
|
||||
public RenderPipeline build() {
|
||||
return delegate.build();
|
||||
}
|
||||
|
||||
public RenderPipeline buildAndRegister() {
|
||||
return LoVisualRenderPipelines.registerAddonPipeline(build());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render;
|
||||
|
||||
public enum LoVisualRenderStage {
|
||||
HUD_RAW,
|
||||
HUD_SCALED,
|
||||
HUD_LOGICAL,
|
||||
HUD_RAW_FOREGROUND,
|
||||
HUD_SCALED_FOREGROUND,
|
||||
HUD_LOGICAL_FOREGROUND,
|
||||
WORLD_BEFORE_TRANSLUCENT,
|
||||
WORLD_END_MAIN,
|
||||
WORLD_POST_PROCESS,
|
||||
SCREEN_BEFORE_VANILLA_GUI,
|
||||
SCREEN_AFTER_VANILLA_GUI
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render;
|
||||
|
||||
import com.mojang.blaze3d.buffers.GpuBufferSlice;
|
||||
import dev.loki.lovisual.render.engine.core.system.LoVisualRenderSystem;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public enum LoVisualUniforms {
|
||||
;
|
||||
|
||||
public static GpuBufferSlice write(String name,
|
||||
int std140Size,
|
||||
int expectedWritesPerFrame,
|
||||
UniformWriter writer) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new IllegalArgumentException("Uniform name cannot be blank");
|
||||
}
|
||||
if (std140Size <= 0) {
|
||||
throw new IllegalArgumentException("Uniform std140 size must be positive");
|
||||
}
|
||||
if (writer == null) {
|
||||
throw new IllegalArgumentException("Uniform writer cannot be null");
|
||||
}
|
||||
return LoVisualRenderSystem.uniforms().write(name, std140Size, expectedWritesPerFrame, writer::write);
|
||||
}
|
||||
|
||||
public static GpuBufferSlice writeCached(String name,
|
||||
int std140Size,
|
||||
int expectedWritesPerFrame,
|
||||
int updateEveryFrames,
|
||||
boolean force,
|
||||
UniformWriter writer) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new IllegalArgumentException("Uniform name cannot be blank");
|
||||
}
|
||||
if (std140Size <= 0) {
|
||||
throw new IllegalArgumentException("Uniform std140 size must be positive");
|
||||
}
|
||||
if (writer == null) {
|
||||
throw new IllegalArgumentException("Uniform writer cannot be null");
|
||||
}
|
||||
return LoVisualRenderSystem.uniforms().writeCached(
|
||||
name,
|
||||
std140Size,
|
||||
expectedWritesPerFrame,
|
||||
updateEveryFrames,
|
||||
force,
|
||||
writer::write
|
||||
);
|
||||
}
|
||||
|
||||
public static GpuBufferSlice current(String name) {
|
||||
if (name == null || name.isBlank()) return null;
|
||||
return LoVisualRenderSystem.uniforms().current(name);
|
||||
}
|
||||
|
||||
public static void invalidate(String name) {
|
||||
if (name == null || name.isBlank()) return;
|
||||
LoVisualRenderSystem.uniforms().invalidate(name);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface UniformWriter {
|
||||
void write(ByteBuffer buffer);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render.callback;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface LoVisualPostProcessCallback {
|
||||
public boolean render(LoVisualPostProcessContext context);
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render.callback;
|
||||
|
||||
import com.mojang.blaze3d.textures.GpuTextureView;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessPass;
|
||||
import net.minecraft.client.Minecraft;
|
||||
|
||||
public record LoVisualPostProcessContext(
|
||||
String addonId,
|
||||
String passId,
|
||||
PostProcessPass.Phase phase,
|
||||
GpuTextureView source,
|
||||
GpuTextureView destination,
|
||||
float tickDelta
|
||||
) {
|
||||
public Minecraft client() {
|
||||
return Minecraft.getInstance();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render.callback;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface LoVisualRenderCallback {
|
||||
public void render(LoVisualRenderContext context);
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render.callback;
|
||||
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
|
||||
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import dev.loki.lovisual.features.module.phase.HudPhase;
|
||||
import dev.loki.lovisual.features.module.phase.WorldPhase;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
|
||||
public record LoVisualRenderContext(
|
||||
String addonId,
|
||||
String callbackId,
|
||||
LoVisualRenderStage stage,
|
||||
HudPhase hudPhase,
|
||||
WorldPhase worldPhase,
|
||||
Renderer2D renderer2D,
|
||||
Renderer3D renderer3D,
|
||||
Renderer3D depthRenderer3D,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor guiContext,
|
||||
PoseStack poseStack,
|
||||
float tickDelta
|
||||
) {
|
||||
public Minecraft client() {
|
||||
return Minecraft.getInstance();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.compat.xaero;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xaero.common.minimap.waypoints.Waypoint;
|
||||
import xaero.map.mods.SupportXaeroMinimap;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Kept as a no-op compatibility bridge for older mixin code paths.
|
||||
* @xwp markers are now inserted into Xaero's real waypoint sets by {@link XaeroWaypointRuntime},
|
||||
* otherwise World Map/minimap hover, open and delete logic cannot see them.
|
||||
*/
|
||||
public enum XaeroCommandWaypointCompat {
|
||||
;
|
||||
|
||||
public static List<Waypoint> getMinimapWaypoints() {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
public static List<xaero.map.mods.gui.Waypoint> getWorldMapWaypoints(@Nullable SupportXaeroMinimap minimap) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,229 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.compat.xaero;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.level.Level;
|
||||
import xaero.common.HudMod;
|
||||
import xaero.common.minimap.waypoints.Waypoint;
|
||||
import xaero.hud.minimap.BuiltInHudModules;
|
||||
import xaero.hud.minimap.module.MinimapSession;
|
||||
import xaero.hud.minimap.waypoint.WaypointColor;
|
||||
import xaero.hud.minimap.waypoint.WaypointPurpose;
|
||||
import xaero.hud.minimap.waypoint.set.WaypointSet;
|
||||
import xaero.hud.minimap.world.MinimapWorld;
|
||||
import xaero.hud.minimap.world.MinimapWorldManager;
|
||||
import xaero.hud.path.XaeroPath;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class XaeroWaypointRuntime {
|
||||
private XaeroWaypointRuntime() {
|
||||
}
|
||||
|
||||
static XaeroWaypointStore.RuntimeAddResult addFromCurrentDimension(int x,
|
||||
int y,
|
||||
int z,
|
||||
String name,
|
||||
boolean dualDefault) {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.level == null) {
|
||||
return fail("No client world is loaded.");
|
||||
}
|
||||
|
||||
MinimapSession session = currentSession();
|
||||
if (session == null) {
|
||||
return fail("Xaero minimap session is not ready.");
|
||||
}
|
||||
|
||||
List<XaeroWaypointStore.Marker> added = new ArrayList<>(2);
|
||||
ResourceKey<Level> currentDim = mc.level.dimension();
|
||||
boolean overworld = currentDim == Level.OVERWORLD;
|
||||
boolean nether = currentDim == Level.NETHER;
|
||||
|
||||
if (dualDefault && overworld) {
|
||||
addToWorld(session, Level.OVERWORLD, x, y, z, name, "overworld", added);
|
||||
addToWorld(session, Level.NETHER, XaeroWaypointStore.netherCoord(x), y, XaeroWaypointStore.netherCoord(z), name, "nether", added);
|
||||
return new XaeroWaypointStore.RuntimeAddResult(true,
|
||||
"Added dual Xaero marker: " + XaeroWaypointStore.format(x, y, z)
|
||||
+ " / Nether " + XaeroWaypointStore.format(XaeroWaypointStore.netherCoord(x), y, XaeroWaypointStore.netherCoord(z)) + ".",
|
||||
List.copyOf(added));
|
||||
}
|
||||
if (dualDefault && nether) {
|
||||
addToWorld(session, Level.NETHER, x, y, z, name, "nether", added);
|
||||
addToWorld(session, Level.OVERWORLD, x * 8, y, z * 8, name, "overworld", added);
|
||||
return new XaeroWaypointStore.RuntimeAddResult(true,
|
||||
"Added dual Xaero marker: Nether " + XaeroWaypointStore.format(x, y, z)
|
||||
+ " / Overworld " + XaeroWaypointStore.format(x * 8, y, z * 8) + ".",
|
||||
List.copyOf(added));
|
||||
}
|
||||
|
||||
addToWorld(session, currentDim, x, y, z, name, XaeroWaypointStore.dimensionId(currentDim.identifier()), added);
|
||||
return new XaeroWaypointStore.RuntimeAddResult(true,
|
||||
"Added Xaero marker: " + XaeroWaypointStore.format(x, y, z) + ".",
|
||||
List.copyOf(added));
|
||||
}
|
||||
|
||||
static boolean remove(XaeroWaypointStore.Marker marker) {
|
||||
if (!(marker.waypointSetHandle() instanceof WaypointSet set)
|
||||
|| !(marker.waypointHandle() instanceof Waypoint waypoint)) {
|
||||
return true;
|
||||
}
|
||||
set.remove(waypoint);
|
||||
markChanged();
|
||||
return true;
|
||||
}
|
||||
|
||||
static boolean exists(XaeroWaypointStore.Marker marker) {
|
||||
if (!(marker.waypointSetHandle() instanceof WaypointSet set)
|
||||
|| !(marker.waypointHandle() instanceof Waypoint waypoint)) {
|
||||
return false;
|
||||
}
|
||||
for (Waypoint existing : set.getWaypoints()) {
|
||||
if (existing == waypoint) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void addToWorld(MinimapSession session,
|
||||
ResourceKey<Level> dimension,
|
||||
int x,
|
||||
int y,
|
||||
int z,
|
||||
String name,
|
||||
String kind,
|
||||
List<XaeroWaypointStore.Marker> out) {
|
||||
MinimapWorld world = resolveWorld(session, dimension);
|
||||
if (world == null) {
|
||||
throw new IllegalStateException("Could not resolve Xaero world for " + dimension.identifier());
|
||||
}
|
||||
|
||||
WaypointSet set = currentSet(world);
|
||||
Waypoint waypoint = new Waypoint(
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
XaeroWaypointStore.displayName(name, kind),
|
||||
XaeroWaypointStore.DEFAULT_SYMBOL,
|
||||
WaypointColor.GOLD,
|
||||
WaypointPurpose.NORMAL,
|
||||
true,
|
||||
true
|
||||
);
|
||||
waypoint.setTemporary(true);
|
||||
waypoint.setYIncluded(true);
|
||||
waypoint.setDisabled(false);
|
||||
set.add(waypoint);
|
||||
out.add(XaeroWaypointStore.createMarker(
|
||||
XaeroWaypointStore.dimensionId(dimension.identifier()),
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
waypoint.getName(),
|
||||
waypoint.getSymbol(),
|
||||
set.getName(),
|
||||
kind,
|
||||
set,
|
||||
waypoint
|
||||
));
|
||||
markChanged();
|
||||
}
|
||||
|
||||
private static WaypointSet currentSet(MinimapWorld world) {
|
||||
WaypointSet set = world.getCurrentWaypointSet();
|
||||
if (set != null) {
|
||||
return set;
|
||||
}
|
||||
String setId = world.getCurrentWaypointSetId();
|
||||
if (setId == null || setId.isBlank()) {
|
||||
setId = XaeroWaypointStore.SET;
|
||||
world.setCurrentWaypointSetId(setId);
|
||||
}
|
||||
set = world.getWaypointSet(setId);
|
||||
if (set == null) {
|
||||
world.addWaypointSet(setId);
|
||||
set = world.getWaypointSet(setId);
|
||||
}
|
||||
if (set == null) {
|
||||
throw new IllegalStateException("Could not resolve Xaero waypoint set.");
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
private static MinimapWorld resolveWorld(MinimapSession session, ResourceKey<Level> dimension) {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
MinimapWorldManager manager = session.getWorldManager();
|
||||
if (mc != null && mc.level != null && mc.level.dimension() == dimension) {
|
||||
return manager.getCurrentWorld();
|
||||
}
|
||||
|
||||
XaeroPath rootPath = session.getWorldState().getCurrentRootContainerPath();
|
||||
XaeroPath currentWorldPath = session.getWorldState().getCurrentWorldPath();
|
||||
if (rootPath == null || currentWorldPath == null) {
|
||||
return manager.getCurrentWorld();
|
||||
}
|
||||
|
||||
String dimensionNode = session.getDimensionHelper().getDimensionDirectoryName(dimension);
|
||||
if (dimensionNode == null || dimensionNode.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String worldNode = null;
|
||||
try {
|
||||
boolean worldMap = HudMod.INSTANCE != null
|
||||
&& HudMod.INSTANCE.getSupportMods() != null
|
||||
&& HudMod.INSTANCE.getSupportMods().worldmap();
|
||||
worldNode = session.getWorldStateUpdater().getPotentialWorldNode(dimension, worldMap);
|
||||
} catch (Throwable ignored) {
|
||||
// Fallback below keeps the marker in the same multiworld node as the current dimension.
|
||||
}
|
||||
if (worldNode == null || worldNode.isBlank()) {
|
||||
worldNode = currentWorldPath.getLastNode();
|
||||
}
|
||||
|
||||
XaeroPath worldPath = rootPath.resolve(dimensionNode).resolve(worldNode);
|
||||
MinimapWorld world = manager.getWorld(worldPath);
|
||||
if (world != null) {
|
||||
world.setDimId(dimension);
|
||||
}
|
||||
return world;
|
||||
}
|
||||
|
||||
private static MinimapSession currentSession() {
|
||||
Object session = BuiltInHudModules.MINIMAP.getCurrentSession();
|
||||
return session instanceof MinimapSession minimapSession ? minimapSession : null;
|
||||
}
|
||||
|
||||
private static void markChanged() {
|
||||
MinimapSession session = currentSession();
|
||||
if (session != null && session.getWaypointSession() != null) {
|
||||
session.getWaypointSession().setSetChangedTime(System.currentTimeMillis());
|
||||
}
|
||||
requestWorldMapRefresh();
|
||||
}
|
||||
|
||||
private static void requestWorldMapRefresh() {
|
||||
try {
|
||||
Class<?> supportMods = Class.forName("xaero.map.mods.SupportMods");
|
||||
Object support = supportMods.getField("xaeroMinimap").get(null);
|
||||
if (support != null) {
|
||||
support.getClass().getMethod("requestWaypointsRefresh").invoke(support);
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
// World Map is optional; minimap hover/list deletion works through the real Xaero set without it.
|
||||
}
|
||||
}
|
||||
|
||||
private static XaeroWaypointStore.RuntimeAddResult fail(String message) {
|
||||
return new XaeroWaypointStore.RuntimeAddResult(false, message, List.of());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,249 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.compat.xaero;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.world.level.Level;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
public enum XaeroWaypointStore {
|
||||
;
|
||||
|
||||
public static final String SET = "lovisual";
|
||||
public static final String DEFAULT_NAME = "LoVisual";
|
||||
public static final String DEFAULT_SYMBOL = "C";
|
||||
|
||||
private static final AtomicLong NEXT_ID = new AtomicLong(1L);
|
||||
private static final CopyOnWriteArrayList<Marker> MARKERS = new CopyOnWriteArrayList<>();
|
||||
|
||||
public static AddResult addFromCurrentDimension(int x, int y, int z, String name, boolean dualDefault) {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.level == null) {
|
||||
return new AddResult(false, 0, "No client world is loaded.");
|
||||
}
|
||||
|
||||
String safeName = sanitizeName(name);
|
||||
try {
|
||||
RuntimeAddResult runtime = XaeroWaypointRuntime.addFromCurrentDimension(x, y, z, safeName, dualDefault);
|
||||
if (!runtime.success()) {
|
||||
return new AddResult(false, 0, runtime.message());
|
||||
}
|
||||
MARKERS.addAll(runtime.markers());
|
||||
return new AddResult(true, runtime.markers().size(), runtime.message());
|
||||
} catch (NoClassDefFoundError | ExceptionInInitializerError error) {
|
||||
return new AddResult(false, 0, "Xaero waypoint runtime is not available.");
|
||||
} catch (Throwable throwable) {
|
||||
return new AddResult(false, 0, "Failed to add Xaero marker: " + throwable.getClass().getSimpleName() + ".");
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Marker> currentDimensionMarkers() {
|
||||
pruneMissing();
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.level == null || MARKERS.isEmpty()) return List.of();
|
||||
String dim = dimensionId(mc.level.dimension().identifier());
|
||||
List<Marker> out = new ArrayList<>();
|
||||
for (Marker marker : MARKERS) {
|
||||
if (marker.dimensionId().equals(dim)) {
|
||||
out.add(marker);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static List<Marker> markers() {
|
||||
pruneMissing();
|
||||
return List.copyOf(MARKERS);
|
||||
}
|
||||
|
||||
public static RemoveResult remove(String selector) {
|
||||
pruneMissing();
|
||||
if (MARKERS.isEmpty()) {
|
||||
return new RemoveResult(true, 0, "No LoVisual Xaero markers to remove.");
|
||||
}
|
||||
|
||||
List<Marker> targets = select(selector);
|
||||
if (targets.isEmpty()) {
|
||||
return new RemoveResult(false, 0, "No matching LoVisual Xaero marker: " + selector + ".");
|
||||
}
|
||||
|
||||
int removed = 0;
|
||||
for (Marker marker : targets) {
|
||||
if (removeMarker(marker)) {
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
if (removed == 0) {
|
||||
return new RemoveResult(false, 0, "No LoVisual Xaero markers were removed.");
|
||||
}
|
||||
return new RemoveResult(true, removed, "Removed Xaero markers: " + removed + ".");
|
||||
}
|
||||
|
||||
public static int clear() {
|
||||
return remove(null).count();
|
||||
}
|
||||
|
||||
static Marker createMarker(String dimensionId,
|
||||
int x,
|
||||
int y,
|
||||
int z,
|
||||
String name,
|
||||
String symbol,
|
||||
String set,
|
||||
String kind,
|
||||
Object waypointSetHandle,
|
||||
Object waypointHandle) {
|
||||
return new Marker(
|
||||
NEXT_ID.getAndIncrement(),
|
||||
dimensionId,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
name,
|
||||
symbol,
|
||||
set,
|
||||
kind,
|
||||
System.currentTimeMillis(),
|
||||
waypointSetHandle,
|
||||
waypointHandle
|
||||
);
|
||||
}
|
||||
|
||||
private static List<Marker> select(String selector) {
|
||||
String normalized = selector == null ? "" : selector.trim();
|
||||
if (normalized.isEmpty()
|
||||
|| "all".equalsIgnoreCase(normalized)
|
||||
|| "*".equals(normalized)) {
|
||||
return new ArrayList<>(MARKERS);
|
||||
}
|
||||
|
||||
Integer index = parsePositiveInt(normalized);
|
||||
if (index != null) {
|
||||
List<Marker> snapshot = markers();
|
||||
int zeroIndex = index - 1;
|
||||
if (zeroIndex >= 0 && zeroIndex < snapshot.size()) {
|
||||
return List.of(snapshot.get(zeroIndex));
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
String lower = normalized.toLowerCase(Locale.ROOT);
|
||||
List<Marker> out = new ArrayList<>();
|
||||
for (Marker marker : MARKERS) {
|
||||
if (marker.name().toLowerCase(Locale.ROOT).contains(lower)
|
||||
|| marker.kind().toLowerCase(Locale.ROOT).contains(lower)
|
||||
|| marker.dimensionId().toLowerCase(Locale.ROOT).contains(lower)) {
|
||||
out.add(marker);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean removeMarker(Marker marker) {
|
||||
boolean removedFromXaero = true;
|
||||
try {
|
||||
removedFromXaero = XaeroWaypointRuntime.remove(marker);
|
||||
} catch (NoClassDefFoundError | ExceptionInInitializerError ignored) {
|
||||
removedFromXaero = true;
|
||||
} catch (Throwable ignored) {
|
||||
removedFromXaero = false;
|
||||
}
|
||||
boolean removedFromStore = MARKERS.remove(marker);
|
||||
return removedFromStore && removedFromXaero;
|
||||
}
|
||||
|
||||
private static void pruneMissing() {
|
||||
if (MARKERS.isEmpty()) return;
|
||||
try {
|
||||
Iterator<Marker> iterator = MARKERS.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Marker marker = iterator.next();
|
||||
if (!XaeroWaypointRuntime.exists(marker)) {
|
||||
MARKERS.remove(marker);
|
||||
}
|
||||
}
|
||||
} catch (NoClassDefFoundError | ExceptionInInitializerError ignored) {
|
||||
MARKERS.clear();
|
||||
} catch (Throwable ignored) {
|
||||
// Keep the in-memory index if Xaero is mid-session reload or unavailable for a tick.
|
||||
}
|
||||
}
|
||||
|
||||
static int netherCoord(int overworldCoord) {
|
||||
return (int) Math.round(overworldCoord / 8.0);
|
||||
}
|
||||
|
||||
static String dimensionId(Identifier id) {
|
||||
return id == null ? "" : id.toString();
|
||||
}
|
||||
|
||||
static String sanitizeName(String name) {
|
||||
if (name == null || name.isBlank()) return DEFAULT_NAME;
|
||||
String trimmed = name.trim();
|
||||
return trimmed.length() > 40 ? trimmed.substring(0, 40) : trimmed;
|
||||
}
|
||||
|
||||
static String displayName(String name, String kind) {
|
||||
String safeName = sanitizeName(name);
|
||||
if (kind == null || kind.isBlank() || kind.contains(":")) return safeName;
|
||||
return safeName + " " + kind;
|
||||
}
|
||||
|
||||
static String format(int x, int y, int z) {
|
||||
return String.format(Locale.ROOT, "%d %d %d", x, y, z);
|
||||
}
|
||||
|
||||
private static Integer parsePositiveInt(String value) {
|
||||
try {
|
||||
int parsed = Integer.parseInt(value);
|
||||
return parsed <= 0 ? null : parsed;
|
||||
} catch (NumberFormatException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isOverworld() {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
return mc != null && mc.level != null && mc.level.dimension() == Level.OVERWORLD;
|
||||
}
|
||||
|
||||
static boolean isNether() {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
return mc != null && mc.level != null && mc.level.dimension() == Level.NETHER;
|
||||
}
|
||||
|
||||
public record Marker(long id,
|
||||
String dimensionId,
|
||||
int x,
|
||||
int y,
|
||||
int z,
|
||||
String name,
|
||||
String symbol,
|
||||
String set,
|
||||
String kind,
|
||||
long createdAtMs,
|
||||
Object waypointSetHandle,
|
||||
Object waypointHandle) {
|
||||
}
|
||||
|
||||
public record AddResult(boolean success, int count, String message) {
|
||||
}
|
||||
|
||||
public record RemoveResult(boolean success, int count, String message) {
|
||||
}
|
||||
|
||||
static record RuntimeAddResult(boolean success, String message, List<Marker> markers) {
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue